android-ui-analyser 0.48.0__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.
Files changed (226) hide show
  1. android_ui_analyser/__init__.py +7 -0
  2. android_ui_analyser/agent_results.py +224 -0
  3. android_ui_analyser/agent_run.py +452 -0
  4. android_ui_analyser/annotate.py +95 -0
  5. android_ui_analyser/api_cartridge.py +856 -0
  6. android_ui_analyser/api_map.py +416 -0
  7. android_ui_analyser/api_session.py +286 -0
  8. android_ui_analyser/api_spec_diff.py +476 -0
  9. android_ui_analyser/api_usage.py +767 -0
  10. android_ui_analyser/app_database.py +931 -0
  11. android_ui_analyser/app_datastore.py +1036 -0
  12. android_ui_analyser/assertions.py +375 -0
  13. android_ui_analyser/atomic.py +60 -0
  14. android_ui_analyser/autopilot.py +164 -0
  15. android_ui_analyser/binary_dump.py +84 -0
  16. android_ui_analyser/bonjour.py +227 -0
  17. android_ui_analyser/caller_latency.py +357 -0
  18. android_ui_analyser/candidate_flows.py +140 -0
  19. android_ui_analyser/capabilities.py +484 -0
  20. android_ui_analyser/capture.py +1101 -0
  21. android_ui_analyser/capture_evidence.py +209 -0
  22. android_ui_analyser/capture_sidecar.py +452 -0
  23. android_ui_analyser/chrome_extension/icons/attached-128.png +0 -0
  24. android_ui_analyser/chrome_extension/icons/attached-16.png +0 -0
  25. android_ui_analyser/chrome_extension/icons/attached-32.png +0 -0
  26. android_ui_analyser/chrome_extension/icons/attached-48.png +0 -0
  27. android_ui_analyser/chrome_extension/icons/attached.svg +12 -0
  28. android_ui_analyser/chrome_extension/icons/idle-16.png +0 -0
  29. android_ui_analyser/chrome_extension/icons/idle-32.png +0 -0
  30. android_ui_analyser/chrome_extension/icons/idle.svg +12 -0
  31. android_ui_analyser/chrome_extension/manifest.json +29 -0
  32. android_ui_analyser/chrome_extension/open.html +15 -0
  33. android_ui_analyser/chrome_extension/open.js +21 -0
  34. android_ui_analyser/chrome_extension/popup.css +51 -0
  35. android_ui_analyser/chrome_extension/popup.html +18 -0
  36. android_ui_analyser/chrome_extension/popup.js +29 -0
  37. android_ui_analyser/chrome_extension/worker.js +436 -0
  38. android_ui_analyser/chrome_extension_setup.py +228 -0
  39. android_ui_analyser/chrome_native_host.py +132 -0
  40. android_ui_analyser/cli.py +12210 -0
  41. android_ui_analyser/cli_development_tools.py +234 -0
  42. android_ui_analyser/cli_invocations.py +280 -0
  43. android_ui_analyser/clock.py +57 -0
  44. android_ui_analyser/coaching.py +640 -0
  45. android_ui_analyser/config.py +1312 -0
  46. android_ui_analyser/credential_exec.py +411 -0
  47. android_ui_analyser/credentials.py +333 -0
  48. android_ui_analyser/daemon.py +2337 -0
  49. android_ui_analyser/dashboard.py +7514 -0
  50. android_ui_analyser/data/api-cartridge-sample.yaml +96 -0
  51. android_ui_analyser/data/aua-dashboard-logo.png +0 -0
  52. android_ui_analyser/data/aua-helper.apk +0 -0
  53. android_ui_analyser/data/report-guide.md +93 -0
  54. android_ui_analyser/data/video-player.js +823 -0
  55. android_ui_analyser/device.py +52 -0
  56. android_ui_analyser/device_agent.py +1082 -0
  57. android_ui_analyser/device_ledger.py +1549 -0
  58. android_ui_analyser/devopts.py +206 -0
  59. android_ui_analyser/drive_projection.py +312 -0
  60. android_ui_analyser/drive_rule.py +793 -0
  61. android_ui_analyser/element_handles.py +336 -0
  62. android_ui_analyser/emulator.py +3015 -0
  63. android_ui_analyser/emulator_watchdog.py +215 -0
  64. android_ui_analyser/engine.py +2876 -0
  65. android_ui_analyser/engine_actions.py +2348 -0
  66. android_ui_analyser/engine_analyze.py +1776 -0
  67. android_ui_analyser/engine_apps.py +1889 -0
  68. android_ui_analyser/engine_browser.py +223 -0
  69. android_ui_analyser/engine_capture.py +978 -0
  70. android_ui_analyser/engine_development_tools.py +292 -0
  71. android_ui_analyser/engine_environment.py +1707 -0
  72. android_ui_analyser/engine_flows.py +2757 -0
  73. android_ui_analyser/engine_journeys.py +278 -0
  74. android_ui_analyser/engine_memory.py +812 -0
  75. android_ui_analyser/engine_navigation.py +2701 -0
  76. android_ui_analyser/engine_observation.py +1504 -0
  77. android_ui_analyser/engine_policy.py +1563 -0
  78. android_ui_analyser/engine_previews.py +258 -0
  79. android_ui_analyser/engine_sessions.py +2450 -0
  80. android_ui_analyser/engine_support.py +221 -0
  81. android_ui_analyser/engine_virtual_targets.py +469 -0
  82. android_ui_analyser/engine_waits.py +2474 -0
  83. android_ui_analyser/errors.py +360 -0
  84. android_ui_analyser/evidence.py +169 -0
  85. android_ui_analyser/explore.py +235 -0
  86. android_ui_analyser/flag_values.py +147 -0
  87. android_ui_analyser/flags.py +594 -0
  88. android_ui_analyser/flow_artifacts.py +309 -0
  89. android_ui_analyser/flows.py +2241 -0
  90. android_ui_analyser/gate.py +170 -0
  91. android_ui_analyser/guide.py +2604 -0
  92. android_ui_analyser/hierarchy.py +281 -0
  93. android_ui_analyser/icon_names.py +240 -0
  94. android_ui_analyser/identity.py +454 -0
  95. android_ui_analyser/imaging.py +288 -0
  96. android_ui_analyser/jobs.py +569 -0
  97. android_ui_analyser/journal.py +1011 -0
  98. android_ui_analyser/journal_stats.py +122 -0
  99. android_ui_analyser/journeys.py +227 -0
  100. android_ui_analyser/layout.py +225 -0
  101. android_ui_analyser/leases.py +2158 -0
  102. android_ui_analyser/llm_route.py +316 -0
  103. android_ui_analyser/logcat.py +816 -0
  104. android_ui_analyser/mcp_development_tools.py +95 -0
  105. android_ui_analyser/mcp_profiles.py +78 -0
  106. android_ui_analyser/mcp_report_tools.py +79 -0
  107. android_ui_analyser/mcp_server.py +5514 -0
  108. android_ui_analyser/memory.py +5655 -0
  109. android_ui_analyser/memory_sqlite.py +128 -0
  110. android_ui_analyser/merge.py +195 -0
  111. android_ui_analyser/mic.py +1069 -0
  112. android_ui_analyser/model_control.py +184 -0
  113. android_ui_analyser/network.py +297 -0
  114. android_ui_analyser/network_profiles.py +460 -0
  115. android_ui_analyser/observation_contract.py +170 -0
  116. android_ui_analyser/perf.py +410 -0
  117. android_ui_analyser/platforms/__init__.py +159 -0
  118. android_ui_analyser/platforms/android.py +807 -0
  119. android_ui_analyser/platforms/android_apk.py +331 -0
  120. android_ui_analyser/platforms/android_bounded_reads.py +113 -0
  121. android_ui_analyser/platforms/android_cli.py +844 -0
  122. android_ui_analyser/platforms/android_cli_catalogue.json +2555 -0
  123. android_ui_analyser/platforms/android_device.py +2890 -0
  124. android_ui_analyser/platforms/android_recording.py +789 -0
  125. android_ui_analyser/platforms/android_runtime.py +141 -0
  126. android_ui_analyser/platforms/android_supervision.py +83 -0
  127. android_ui_analyser/platforms/android_transport.py +225 -0
  128. android_ui_analyser/platforms/api.py +5 -0
  129. android_ui_analyser/platforms/base.py +596 -0
  130. android_ui_analyser/platforms/chrome_extension.py +902 -0
  131. android_ui_analyser/platforms/conformance.py +328 -0
  132. android_ui_analyser/platforms/contracts.py +309 -0
  133. android_ui_analyser/platforms/diagnostics.py +301 -0
  134. android_ui_analyser/platforms/drag_path.py +23 -0
  135. android_ui_analyser/platforms/geometry.py +133 -0
  136. android_ui_analyser/platforms/identity.py +187 -0
  137. android_ui_analyser/platforms/ios.py +434 -0
  138. android_ui_analyser/platforms/ios_database.py +404 -0
  139. android_ui_analyser/platforms/ios_device.py +290 -0
  140. android_ui_analyser/platforms/ios_files.py +45 -0
  141. android_ui_analyser/platforms/ios_preferences.py +237 -0
  142. android_ui_analyser/platforms/ios_runtime.py +516 -0
  143. android_ui_analyser/platforms/ios_tools.py +428 -0
  144. android_ui_analyser/platforms/ios_tree.py +456 -0
  145. android_ui_analyser/platforms/options_transport.py +185 -0
  146. android_ui_analyser/platforms/registry.py +234 -0
  147. android_ui_analyser/platforms/runtime.py +645 -0
  148. android_ui_analyser/platforms/services.py +450 -0
  149. android_ui_analyser/platforms/supervision.py +32 -0
  150. android_ui_analyser/platforms/virtual_targets.py +330 -0
  151. android_ui_analyser/platforms/web.py +709 -0
  152. android_ui_analyser/platforms/web_bounded_reads.py +78 -0
  153. android_ui_analyser/platforms/web_cdp.py +296 -0
  154. android_ui_analyser/platforms/web_runtime.py +342 -0
  155. android_ui_analyser/platforms/web_tools.py +1790 -0
  156. android_ui_analyser/platforms/web_tree.py +230 -0
  157. android_ui_analyser/policy.py +1142 -0
  158. android_ui_analyser/policy_doctor.py +244 -0
  159. android_ui_analyser/policy_health.py +163 -0
  160. android_ui_analyser/policy_trace.py +220 -0
  161. android_ui_analyser/prepare.py +993 -0
  162. android_ui_analyser/prepare_run.py +329 -0
  163. android_ui_analyser/prepare_store.py +282 -0
  164. android_ui_analyser/projection.py +919 -0
  165. android_ui_analyser/providers/__init__.py +6 -0
  166. android_ui_analyser/providers/base.py +364 -0
  167. android_ui_analyser/providers/detection/__init__.py +1 -0
  168. android_ui_analyser/providers/detection/omniparser.py +211 -0
  169. android_ui_analyser/providers/detection/yolo.py +162 -0
  170. android_ui_analyser/providers/grounding/__init__.py +1 -0
  171. android_ui_analyser/providers/grounding/_common.py +239 -0
  172. android_ui_analyser/providers/grounding/_screen_analysis.py +169 -0
  173. android_ui_analyser/providers/grounding/anthropic.py +87 -0
  174. android_ui_analyser/providers/grounding/gemini.py +189 -0
  175. android_ui_analyser/providers/grounding/local_vllm.py +90 -0
  176. android_ui_analyser/providers/grounding/openai.py +183 -0
  177. android_ui_analyser/providers/icon_names/__init__.py +1 -0
  178. android_ui_analyser/providers/icon_names/hosted_vision.py +96 -0
  179. android_ui_analyser/providers/ocr/__init__.py +1 -0
  180. android_ui_analyser/providers/ocr/apple_vision.py +116 -0
  181. android_ui_analyser/providers/ocr/easyocr.py +84 -0
  182. android_ui_analyser/providers/ocr/paddleocr.py +94 -0
  183. android_ui_analyser/providers/ocr/rapidocr.py +86 -0
  184. android_ui_analyser/providers/ocr/tesseract.py +90 -0
  185. android_ui_analyser/providers/planner/__init__.py +1 -0
  186. android_ui_analyser/providers/planner/_common.py +109 -0
  187. android_ui_analyser/providers/planner/gemini_flash.py +73 -0
  188. android_ui_analyser/providers/policy/__init__.py +1 -0
  189. android_ui_analyser/providers/policy/functiongemma.py +1065 -0
  190. android_ui_analyser/providers/policy/gemma4.py +488 -0
  191. android_ui_analyser/providers/policy/qwen3.py +269 -0
  192. android_ui_analyser/providers/registry.py +272 -0
  193. android_ui_analyser/proxy_mock.py +2215 -0
  194. android_ui_analyser/push.py +201 -0
  195. android_ui_analyser/read_budget.py +68 -0
  196. android_ui_analyser/reconcile.py +1316 -0
  197. android_ui_analyser/recordings.py +347 -0
  198. android_ui_analyser/release_check.py +311 -0
  199. android_ui_analyser/release_install.py +237 -0
  200. android_ui_analyser/report.py +244 -0
  201. android_ui_analyser/resources/functiongemma/GEMMA_PROHIBITED_USE_POLICY.md +72 -0
  202. android_ui_analyser/resources/functiongemma/LICENSE +221 -0
  203. android_ui_analyser/resources/functiongemma/MODEL_CARD.md +96 -0
  204. android_ui_analyser/resources/functiongemma/NOTICE +1 -0
  205. android_ui_analyser/resources/functiongemma/adapter_config.json +11 -0
  206. android_ui_analyser/resources/functiongemma/adapters.safetensors +0 -0
  207. android_ui_analyser/resources/functiongemma/adapters.safetensors.NOTICE +4 -0
  208. android_ui_analyser/resources/functiongemma/manifest.json +112 -0
  209. android_ui_analyser/routing.py +190 -0
  210. android_ui_analyser/schema.py +1160 -0
  211. android_ui_analyser/scroll_geom.py +329 -0
  212. android_ui_analyser/selectors.py +732 -0
  213. android_ui_analyser/session.py +3400 -0
  214. android_ui_analyser/session_artifacts.py +448 -0
  215. android_ui_analyser/session_contracts.py +292 -0
  216. android_ui_analyser/sqlite_schema.py +57 -0
  217. android_ui_analyser/suite.py +316 -0
  218. android_ui_analyser/target_activity.py +81 -0
  219. android_ui_analyser/teardown.py +591 -0
  220. android_ui_analyser/teardown_watchdog.py +180 -0
  221. android_ui_analyser/webview.py +257 -0
  222. android_ui_analyser-0.48.0.dist-info/METADATA +2431 -0
  223. android_ui_analyser-0.48.0.dist-info/RECORD +226 -0
  224. android_ui_analyser-0.48.0.dist-info/WHEEL +4 -0
  225. android_ui_analyser-0.48.0.dist-info/entry_points.txt +3 -0
  226. android_ui_analyser-0.48.0.dist-info/licenses/LICENSE +26 -0
@@ -0,0 +1,7 @@
1
+ """android-ui-analyser — fast, configurable Android UI perception + action for agents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.48.0"
6
+
7
+ __all__ = ["__version__"]
@@ -0,0 +1,224 @@
1
+ """A single caller view of CLI and MCP results, without another device read.
2
+
3
+ The transport hands this module the payload it actually received. Normalization does not
4
+ recover missing output, replay an action, load an image, or carry an older screen forward.
5
+ An unsuccessful action may still return useful evidence; those are separate facts here.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from copy import deepcopy
12
+ from typing import Any
13
+
14
+ from .observation_contract import build_observation_contract, observation_payload
15
+
16
+ _UI_KEYS = frozenset({"schema_version", "screen", "elements", "elements_count", "meta"})
17
+
18
+
19
+ def _error(code: str, message: str, **details: Any) -> dict[str, Any]:
20
+ return {"code": code, "message": message, **details}
21
+
22
+
23
+ def _existing_contract(data: dict[str, Any]) -> dict[str, Any]:
24
+ existing = data.get("observation_contract")
25
+ if isinstance(existing, dict):
26
+ return existing
27
+ observation = observation_payload(data)
28
+ meta = observation.get("meta") if observation else None
29
+ existing = meta.get("observation_contract") if isinstance(meta, dict) else None
30
+ return existing if isinstance(existing, dict) else {}
31
+
32
+
33
+ def _without_observation(data: dict[str, Any]) -> dict[str, Any]:
34
+ """Move only a recognized UI shape; unrelated result metadata stays in place."""
35
+ out = dict(data)
36
+ observation = observation_payload(data)
37
+ if observation is data:
38
+ for key in _UI_KEYS:
39
+ out.pop(key, None)
40
+ elif observation is not None:
41
+ out.pop("observation", None)
42
+ out.pop("observation_contract", None)
43
+ return out
44
+
45
+
46
+ def normalize_result(
47
+ payload: Any,
48
+ *,
49
+ command: str,
50
+ context: dict[str, Any] | None = None,
51
+ exit_code: int | None = None,
52
+ transport_error: bool = False,
53
+ ) -> dict[str, Any]:
54
+ """Normalize one already-decoded AUA payload into the versioned agent envelope.
55
+
56
+ Arrays are valid non-UI responses (for example ``list_devices``). Scalars, empty
57
+ objects, and malformed success/error indicators are explicit protocol failures.
58
+ The caller-supplied context is descriptive; this function never resolves ownership.
59
+ """
60
+ copied = deepcopy(payload)
61
+ data = copied if isinstance(copied, dict) else {}
62
+ error: dict[str, Any] | None = None
63
+ source = data
64
+ result: Any = copied
65
+ invalid = not isinstance(copied, (dict, list)) or copied == {}
66
+ if "ok" in data and not isinstance(data["ok"], bool):
67
+ invalid = True
68
+ raw_error = data.get("error")
69
+ if raw_error is not None:
70
+ if not isinstance(raw_error, dict) or not raw_error:
71
+ invalid = True
72
+ else:
73
+ error = dict(raw_error)
74
+ attached = error.pop("result", None)
75
+ if isinstance(attached, dict):
76
+ # Error result fields are the command result. Preserve outer fields too;
77
+ # an attached recovery result takes precedence over earlier stdout data.
78
+ source = {
79
+ **{key: value for key, value in data.items() if key != "error"},
80
+ **attached,
81
+ }
82
+ result = source
83
+ elif attached is not None:
84
+ result = attached
85
+ if isinstance(error.get("observation"), dict) and (
86
+ not isinstance(attached, dict) or observation_payload(attached) is None
87
+ ):
88
+ source = {**source, "observation": error["observation"]}
89
+ if observation_payload(source) is not None:
90
+ error.pop("observation", None)
91
+ if invalid and error is None:
92
+ error = _error("invalid_response", "AUA did not return a valid structured result.")
93
+ if error is None and transport_error:
94
+ error = _error("transport_error", "The transport reported an unsuccessful tool call.")
95
+ if error is None and exit_code not in (None, 0):
96
+ error = _error(
97
+ "cli_exit_error",
98
+ "AUA exited unsuccessfully without a structured error.",
99
+ exit_code=exit_code,
100
+ )
101
+
102
+ observation = observation_payload(source)
103
+ existing = _existing_contract(source)
104
+ contract_source = source
105
+ if observation is not None and not isinstance(observation.get("elements"), list):
106
+ # Journal summaries can report a count without exposing any selectors. They remain
107
+ # useful result data, but an agent cannot address elements it was never given.
108
+ visible = {**observation, "elements": []}
109
+ contract_source = visible if observation is source else {**source, "observation": visible}
110
+ try:
111
+ contract = build_observation_contract(
112
+ contract_source,
113
+ command=command,
114
+ evidence_id=existing.get("evidence_id"),
115
+ fingerprint=existing.get("fingerprint"),
116
+ )
117
+ except (TypeError, ValueError):
118
+ invalid = True
119
+ if error is None:
120
+ error = _error("invalid_response", "AUA returned malformed observation metadata.")
121
+ contract = build_observation_contract({}, command=command)
122
+ # Projection can omit the underlying caveat. A producer's explicit refusal is still
123
+ # authoritative; never turn it back into permission to reuse the returned selectors.
124
+ if existing.get("reusable") is False:
125
+ if contract["reusable"]:
126
+ contract["reason"] = (
127
+ existing.get("reason") or "The producer did not permit selector reuse."
128
+ )
129
+ contract["readiness"] = existing.get("readiness") or "unconfirmed"
130
+ contract["reusable"] = False
131
+ if existing.get("evidence_fresh") is False:
132
+ contract.update(evidence_fresh=False, reusable=False, analyze_needed=True)
133
+ if existing.get("analyze_needed") is True:
134
+ contract["analyze_needed"] = True
135
+
136
+ if observation is not None:
137
+ if observation is source:
138
+ observation = {key: value for key, value in observation.items() if key in _UI_KEYS}
139
+ else:
140
+ observation = dict(observation)
141
+ meta = observation.get("meta")
142
+ if isinstance(meta, dict) and isinstance(meta.get("observation_contract"), dict):
143
+ observation["meta"] = {
144
+ key: value for key, value in meta.items() if key != "observation_contract"
145
+ }
146
+ if isinstance(result, dict):
147
+ result = _without_observation(result)
148
+ result.pop("error", None)
149
+
150
+ ok = not (
151
+ invalid
152
+ or error is not None
153
+ or transport_error
154
+ or exit_code not in (None, 0)
155
+ or data.get("ok") is False
156
+ or source.get("ok") is False
157
+ )
158
+ if not ok and contract.get("action_succeeded") is True:
159
+ # A recovery/partial result may report a successful step inside a failed command.
160
+ # Keep that original fact in result, without claiming overall action success here.
161
+ contract.pop("action_succeeded")
162
+ return {
163
+ "schema_version": 1,
164
+ "ok": ok,
165
+ "error": error,
166
+ "observation": observation,
167
+ "observation_contract": contract,
168
+ "result": result,
169
+ "context": deepcopy(context) if context is not None else {},
170
+ }
171
+
172
+
173
+ def _decode(text: str) -> tuple[Any, bool]:
174
+ try:
175
+ return json.loads(text), True
176
+ except (ValueError, TypeError):
177
+ return None, False
178
+
179
+
180
+ def _stderr_error(stderr: str) -> dict[str, Any] | None:
181
+ # Progress/log lines may precede the structured error, whose emitter writes one JSON
182
+ # line. Inspect complete lines only; never search arbitrary prose for a JSON substring.
183
+ candidates = [stderr, *reversed(stderr.splitlines())]
184
+ for text in candidates:
185
+ value, decoded = _decode(text)
186
+ if decoded and isinstance(value, dict) and value.get("error") is not None:
187
+ return value
188
+ return None
189
+
190
+
191
+ def from_cli(
192
+ stdout: str,
193
+ stderr: str,
194
+ exit_code: int,
195
+ *,
196
+ command: str,
197
+ context: dict[str, Any] | None = None,
198
+ ) -> dict[str, Any]:
199
+ """Read JSON stdout and structured stderr without masking a command failure.
200
+
201
+ Ordinary stderr logs do not invalidate valid stdout. A structured stderr error wins
202
+ even if stdout also contains a result or the subprocess incorrectly exits zero.
203
+ Empty/non-JSON stdout is never fabricated into a successful UI observation.
204
+ """
205
+ payload, decoded = _decode(stdout)
206
+ stderr_payload = _stderr_error(stderr)
207
+ if stderr_payload is not None:
208
+ if decoded and isinstance(payload, dict):
209
+ payload = {**payload, **stderr_payload}
210
+ else:
211
+ payload = stderr_payload
212
+ elif not decoded:
213
+ payload = {
214
+ "error": _error(
215
+ "invalid_response",
216
+ "AUA did not return JSON output.",
217
+ exit_code=exit_code,
218
+ )
219
+ }
220
+ if stderr.strip():
221
+ # Click can reject syntax before AUA's structured error emitter runs. Return
222
+ # its bounded diagnostic to this caller; do not log it or attempt recovery.
223
+ payload["error"]["diagnostic"] = stderr[:2000]
224
+ return normalize_result(payload, command=command, context=context, exit_code=exit_code)
@@ -0,0 +1,452 @@
1
+ """Host-only, explicit run context for callers of the existing CLI.
2
+
3
+ One file binds one caller process and one goal. Commands still run through the installed
4
+ CLI/engine exactly once. No observations, credentials or process environments are saved.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+ import uuid
17
+ from collections.abc import Iterator
18
+ from pathlib import Path
19
+ from typing import Any, Literal
20
+
21
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
22
+
23
+ from . import leases
24
+ from .agent_results import from_cli
25
+ from .config import _ENV_ALIASES, Config
26
+ from .errors import UsageError
27
+ from .schema import OutputFormat
28
+ from .session import load_session_state
29
+
30
+
31
+ class RunContext(BaseModel):
32
+ model_config = ConfigDict(extra="forbid")
33
+
34
+ schema_version: Literal[1] = 1
35
+ run_id: str = Field(min_length=1)
36
+ owner: str = Field(min_length=1)
37
+ caller: dict[str, Any]
38
+ cwd: Path
39
+ config_path: Path
40
+ config_sha256: str = ""
41
+ cache_dir: Path
42
+ platform: str = Field(min_length=1)
43
+ target_id: str | None = None
44
+ session_id: str | None = None
45
+ needs: list[str] = Field(default_factory=list)
46
+
47
+ def public(self) -> dict[str, Any]:
48
+ return self.model_dump(
49
+ mode="json", exclude={"caller", "config_path", "config_sha256", "schema_version"}
50
+ )
51
+
52
+
53
+ def _write_private(path: Path, value: Any, *, create: bool = False) -> None:
54
+ """Atomic private JSON; initialization never overwrites an existing run."""
55
+ if create:
56
+ with open(path, "x", encoding="utf-8", opener=lambda p, f: os.open(p, f, 0o600)) as out:
57
+ json.dump(value, out, ensure_ascii=False)
58
+ return
59
+ fd, temporary = tempfile.mkstemp(prefix=".run-", dir=path.parent)
60
+ try:
61
+ with os.fdopen(fd, "w", encoding="utf-8") as out:
62
+ json.dump(value, out, ensure_ascii=False)
63
+ os.replace(temporary, path)
64
+ finally:
65
+ with contextlib.suppress(FileNotFoundError):
66
+ os.unlink(temporary)
67
+
68
+
69
+ def create_run(
70
+ path: Path, config: Config, *, owner: str | None = None, needs: list[str] | None = None
71
+ ) -> RunContext:
72
+ path = path.expanduser().absolute()
73
+ if path.exists():
74
+ raise UsageError("run context already exists", code="run_context_exists")
75
+ if not config.lease.enabled:
76
+ raise UsageError("a shared run requires device leasing", code="run_context_invalid")
77
+ run_id = uuid.uuid4().hex
78
+ resolved_owner = leases.resolve_owner(owner or f"aua-run-{run_id[:12]}")
79
+ caller = leases.owner_caller(resolved_owner)
80
+ if not caller:
81
+ raise UsageError("cannot identify the run's caller process", code="run_context_owner")
82
+ # The lease registry remains shared. Only observation/session/daemon storage is isolated.
83
+ directory = path.parent / f".{path.name}.{run_id}.d"
84
+ directory.mkdir(mode=0o700, parents=True)
85
+ frozen = config.model_copy(deep=True)
86
+ frozen.cache.dir = str(directory / "cache")
87
+ frozen.output.format = OutputFormat.json
88
+ config_path = directory / "config.json"
89
+ context = RunContext(
90
+ run_id=run_id,
91
+ owner=str(resolved_owner),
92
+ caller=caller,
93
+ cwd=Path.cwd(),
94
+ config_path=config_path,
95
+ cache_dir=Path(frozen.cache.dir),
96
+ platform=frozen.device.platform,
97
+ target_id=frozen.device.serial,
98
+ needs=list(needs or []),
99
+ )
100
+ try:
101
+ _write_private(config_path, frozen.model_dump(mode="json"), create=True)
102
+ context.config_sha256 = hashlib.sha256(config_path.read_bytes()).hexdigest()
103
+ _write_private(path, context.model_dump(mode="json"), create=True)
104
+ except Exception:
105
+ config_path.unlink(missing_ok=True)
106
+ directory.rmdir()
107
+ raise
108
+ return context
109
+
110
+
111
+ def load_run(path: Path) -> RunContext:
112
+ try:
113
+ context = RunContext.model_validate_json(path.expanduser().read_text(encoding="utf-8"))
114
+ except (OSError, ValueError, ValidationError) as exc:
115
+ raise UsageError(
116
+ "run context is missing or invalid; no command was executed",
117
+ code="run_context_invalid",
118
+ hint="Initialize a new run file with `aua run init PATH`.",
119
+ ) from exc
120
+ if leases.owner_caller(leases.resolve_owner(context.owner)) != context.caller:
121
+ raise UsageError(
122
+ "this run belongs to a different caller process; no command was executed",
123
+ code="run_context_owner",
124
+ hint="Use this file from its original agent, or initialize a separate run.",
125
+ )
126
+ try:
127
+ saved = context.config_path.read_bytes()
128
+ if hashlib.sha256(saved).hexdigest() != context.config_sha256:
129
+ raise ValueError("saved configuration changed")
130
+ Config.model_validate_json(saved)
131
+ except (OSError, ValueError) as exc:
132
+ raise UsageError(
133
+ "the run's saved configuration is missing or changed", code="run_context_invalid"
134
+ ) from exc
135
+ return context
136
+
137
+
138
+ @contextlib.contextmanager
139
+ def _run_lock(path: Path) -> Iterator[None]:
140
+ # Reuse AUA's portable host file locking. This is independent of device/lease locks.
141
+ with (
142
+ leases._thread_lock(f"agent-run|{path}"),
143
+ open(
144
+ path.with_suffix(path.suffix + ".lock"),
145
+ "a+",
146
+ encoding="utf-8",
147
+ opener=lambda p, f: os.open(p, f, 0o600),
148
+ ) as handle,
149
+ ):
150
+ backend = leases._acquire_file_lock(handle, exclusive=True)
151
+ try:
152
+ yield
153
+ finally:
154
+ leases._release_file_lock(handle, backend)
155
+
156
+
157
+ def _command_context(arguments: list[str]) -> tuple[dict[str, Any], list[str], dict[str, Any]]:
158
+ """Read the installed Click schema without invoking command callbacks or a device."""
159
+ import click
160
+ from typer.main import get_command
161
+
162
+ from .cli import alias_fields_on_actions, app, hoist_global_options
163
+ from .cli_invocations import current
164
+
165
+ invocation = current()
166
+ previous = invocation.context if invocation is not None else None
167
+ try:
168
+ command = get_command(app)
169
+ args = hoist_global_options(alias_fields_on_actions(arguments))
170
+ ctx = command.make_context("aua", args, resilient_parsing=True)
171
+ root = dict(ctx.params)
172
+ names: list[str] = []
173
+ while isinstance(command, click.Group):
174
+ remaining = [*ctx._protected_args, *ctx.args]
175
+ if not remaining:
176
+ break
177
+ name = remaining[0]
178
+ child = command.get_command(ctx, name)
179
+ if child is None:
180
+ break
181
+ names.append(name)
182
+ ctx = child.make_context(name, remaining[1:], parent=ctx, resilient_parsing=True)
183
+ command = child
184
+ return root, names, dict(ctx.params)
185
+ finally:
186
+ if invocation is not None:
187
+ invocation.context = previous
188
+
189
+
190
+ def _validate_call(context: RunContext, arguments: list[str]) -> str:
191
+ root, names, params = _command_context(arguments)
192
+ if not names:
193
+ raise UsageError("run exec needs an AUA command after --", code="run_context_usage")
194
+ for key in ("config", "profile", "owner", "serial", "platform"):
195
+ if root.get(key) is not None:
196
+ raise UsageError(
197
+ f"--{key} cannot replace saved run context; no command was executed",
198
+ code="run_context_mismatch",
199
+ hint="Set run-wide options before `aua run init`; start a new file to change scope.",
200
+ )
201
+ if root.get("no_lease") or root.get("format") not in (None, "json"):
202
+ raise UsageError("run exec requires leasing and JSON output", code="run_context_mismatch")
203
+ from .cli import _split_needs
204
+
205
+ for value in (root.get("needs"), params.get("needs")):
206
+ if value is not None and _split_needs(value) != context.needs:
207
+ raise UsageError(
208
+ "device requirements cannot replace saved run context", code="run_context_mismatch"
209
+ )
210
+ if names[0] in {"run", "mcp", "daemon", "lease"}:
211
+ raise UsageError("this command cannot run inside a goal wrapper", code="run_context_usage")
212
+ if names[:2] in [
213
+ ["emulator", "start"],
214
+ ["virtual-target", "start"],
215
+ ["virtual-target", "provision"],
216
+ ]:
217
+ raise UsageError("use session start to select the run's target", code="run_context_usage")
218
+ command = "_".join(names).replace("-", "_")
219
+ if context.session_id is None:
220
+ if command != "session_start":
221
+ raise UsageError(
222
+ "this run has no goal session; no command was executed",
223
+ code="run_session_missing",
224
+ hint='Run `aua run exec PATH -- session start --goal "<goal>"` first.',
225
+ )
226
+ return command
227
+ if command == "session_start":
228
+ raise UsageError(
229
+ "one run file holds one goal; initialize another file", code="run_context_mismatch"
230
+ )
231
+ if names[0] == "session" and params.get("session_id") not in (None, context.session_id):
232
+ raise UsageError("session id does not match this run", code="run_context_mismatch")
233
+ if params.get("serial") not in (None, context.target_id):
234
+ raise UsageError("target does not match this run", code="run_context_mismatch")
235
+ if names[0] in {"emulator", "virtual-target"}:
236
+ if names[-1] not in {"status", "list", "stop"}:
237
+ raise UsageError(
238
+ "target lifecycle changes require a separate run", code="run_context_usage"
239
+ )
240
+ if params.get("target_id") not in (None, context.target_id) or params.get("owner") not in (
241
+ None,
242
+ context.owner,
243
+ ):
244
+ raise UsageError("target or owner does not match this run", code="run_context_mismatch")
245
+ if any(
246
+ params.get(key)
247
+ for key in ("all_targets", "all_devices", "mine", "definition_id", "avd")
248
+ ):
249
+ raise UsageError(
250
+ "run cleanup must name only its saved target", code="run_context_mismatch"
251
+ )
252
+ if command == "virtual_target_stop" and params.get("target_id") != context.target_id:
253
+ raise UsageError(
254
+ "pass the run's exact --target-id to stop it", code="run_context_mismatch"
255
+ )
256
+ state = load_session_state(
257
+ context.cache_dir, session_id=context.session_id, platform=context.platform
258
+ )
259
+ if state is None or (state.session_id, state.serial, state.owner) != (
260
+ context.session_id,
261
+ context.target_id,
262
+ context.owner,
263
+ ):
264
+ raise UsageError("saved goal session is missing or mismatched", code="run_session_missing")
265
+ if state.finished_ms is None:
266
+ active = load_session_state(
267
+ context.cache_dir,
268
+ serial=context.target_id,
269
+ owner=context.owner,
270
+ platform=context.platform,
271
+ )
272
+ if active is None or active.session_id != context.session_id:
273
+ raise UsageError(
274
+ "the active goal changed; no command was executed", code="run_context_mismatch"
275
+ )
276
+ elif not (
277
+ command
278
+ in {
279
+ "session_review",
280
+ "session_progress",
281
+ "emulator_status",
282
+ "emulator_stop",
283
+ "virtual_target_status",
284
+ "virtual_target_stop",
285
+ }
286
+ or names[0] == "capture"
287
+ ):
288
+ raise UsageError("this goal has ended; initialize a new run", code="run_session_finished")
289
+ return command
290
+
291
+
292
+ def _invoke_cli(
293
+ arguments: list[str], *, env: dict[str, str], cwd: Path
294
+ ) -> subprocess.CompletedProcess[str]:
295
+ return subprocess.run(
296
+ [sys.executable, "-m", "android_ui_analyser.cli", *arguments],
297
+ env=env,
298
+ cwd=cwd,
299
+ capture_output=True,
300
+ text=True,
301
+ check=False,
302
+ )
303
+
304
+
305
+ def _response_mismatch(context: RunContext, command: str, result: dict[str, Any]) -> bool:
306
+ """Validate identities actually returned, without treating a capture id as a goal."""
307
+ observation = result.get("observation")
308
+ meta = observation.get("meta") if isinstance(observation, dict) else None
309
+ if isinstance(meta, dict) and (
310
+ (context.target_id and meta.get("device_serial") not in (None, context.target_id))
311
+ or meta.get("platform") not in (None, context.platform)
312
+ ):
313
+ return True
314
+ native = result.get("result")
315
+ if command.startswith("session_") and isinstance(native, dict):
316
+ expected = {
317
+ "owner": context.owner,
318
+ "serial": context.target_id,
319
+ "platform": context.platform,
320
+ }
321
+ if context.session_id:
322
+ expected["session_id"] = context.session_id
323
+ return any(
324
+ value is not None and native.get(key) not in (None, value)
325
+ for key, value in expected.items()
326
+ )
327
+ return False
328
+
329
+
330
+ def _refuse_response(result: dict[str, Any], code: str, message: str) -> None:
331
+ result["ok"] = False
332
+ if isinstance(result.get("error"), dict):
333
+ result["error"]["run_context_error"] = {"code": code, "message": message}
334
+ else:
335
+ result["error"] = {"code": code, "message": message}
336
+ result["observation_contract"].update(reusable=False, analyze_needed=True, reason=message)
337
+
338
+
339
+ def execute_run(path: Path, arguments: list[str]) -> tuple[dict[str, Any], int]:
340
+ path = path.expanduser().absolute()
341
+ # Refuse a missing/wrong-owner file before creating even its host lock.
342
+ load_run(path)
343
+ with _run_lock(path):
344
+ context = load_run(path)
345
+ command = _validate_call(context, arguments)
346
+ # Config discovery and ambient AUA overrides cannot redirect the saved run. Secrets
347
+ # referenced by config (e.g. PROVIDER_API_KEY) stay in the current environment only.
348
+ controls = {
349
+ "AUA_CONFIG",
350
+ "AUA_PROFILE",
351
+ "AUA_OWNER",
352
+ "AUA_WORKER_SCOPE",
353
+ "AUA_DAEMON_SOCKET",
354
+ }
355
+ env = {
356
+ key: value
357
+ for key, value in os.environ.items()
358
+ if not (
359
+ key.startswith("AUA_") and ("__" in key or key in _ENV_ALIASES or key in controls)
360
+ )
361
+ }
362
+ env.update(
363
+ AUA_CACHE__DIR=str(context.cache_dir),
364
+ AUA_OWNER=context.owner,
365
+ AUA_WORKER_SCOPE=context.run_id,
366
+ )
367
+ prefix = [
368
+ "--config",
369
+ str(context.config_path),
370
+ "--format",
371
+ "json",
372
+ "--owner",
373
+ context.owner,
374
+ "--log-level",
375
+ Config.model_validate_json(context.config_path.read_bytes()).log_level,
376
+ ]
377
+ if context.target_id:
378
+ prefix += ["--serial", context.target_id]
379
+ if context.needs:
380
+ prefix += ["--needs", ",".join(context.needs)]
381
+ if not context.config_path.is_file():
382
+ raise UsageError("the run's saved configuration is missing", code="run_context_invalid")
383
+ completed = _invoke_cli([*prefix, *arguments], env=env, cwd=context.cwd)
384
+ # The child CLI owns the actual invocation journal, including its failures. The
385
+ # outer process is transport, not a second device call in session accounting.
386
+ if completed.returncode >= 0:
387
+ from .cli_invocations import current
388
+
389
+ invocation = current()
390
+ if invocation is not None:
391
+ invocation.records += 1
392
+ result = from_cli(
393
+ completed.stdout,
394
+ completed.stderr,
395
+ completed.returncode,
396
+ command=command,
397
+ context=context.public(),
398
+ )
399
+ if _response_mismatch(context, command, result):
400
+ _refuse_response(
401
+ result,
402
+ "run_context_mismatch",
403
+ "returned evidence belongs to another run or target; no action was replayed",
404
+ )
405
+ if command == "session_start" and result["ok"]:
406
+ native = result["result"]
407
+ if not isinstance(native, dict) or not all(
408
+ native.get(key) for key in ("session_id", "serial", "owner")
409
+ ):
410
+ _refuse_response(
411
+ result,
412
+ "run_context_mismatch",
413
+ "session start did not return complete run identity; no action was replayed",
414
+ )
415
+ elif native["owner"] != context.owner or (
416
+ context.target_id and native["serial"] != context.target_id
417
+ ):
418
+ _refuse_response(
419
+ result,
420
+ "run_context_mismatch",
421
+ "session start returned another owner or target; no action was replayed",
422
+ )
423
+ else:
424
+ context.session_id = str(native["session_id"])
425
+ context.target_id = str(native["serial"])
426
+ result["context"] = context.public()
427
+ state = load_session_state(
428
+ context.cache_dir, session_id=context.session_id, platform=context.platform
429
+ )
430
+ if (
431
+ _response_mismatch(context, command, result)
432
+ or state is None
433
+ or (state.session_id, state.serial, state.owner)
434
+ != (context.session_id, context.target_id, context.owner)
435
+ ):
436
+ _refuse_response(
437
+ result,
438
+ "run_context_mismatch",
439
+ "session start's returned identity does not match its saved goal; no action was replayed",
440
+ )
441
+ else:
442
+ try:
443
+ _write_private(path, context.model_dump(mode="json"))
444
+ except OSError:
445
+ _refuse_response(
446
+ result,
447
+ "run_context_persist_failed",
448
+ "session started but saving its context failed; keep the returned identity and do not repeat session start",
449
+ )
450
+ return result, completed.returncode if completed.returncode > 0 else (
451
+ 0 if result["ok"] else 1
452
+ )