auto-any 0.1.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.

Potentially problematic release.


This version of auto-any might be problematic. Click here for more details.

Files changed (146) hide show
  1. auto_any/__init__.py +11 -0
  2. auto_any/api/__init__.py +1 -0
  3. auto_any/api/automations.py +209 -0
  4. auto_any/api/packs.py +56 -0
  5. auto_any/api/profiles.py +18 -0
  6. auto_any/api/receipts.py +38 -0
  7. auto_any/browsergate/__init__.py +27 -0
  8. auto_any/browsergate/appium_driver.py +82 -0
  9. auto_any/browsergate/base.py +45 -0
  10. auto_any/browsergate/playwright_driver.py +158 -0
  11. auto_any/browsergate/policy.py +83 -0
  12. auto_any/browsergate/profile_attach.py +30 -0
  13. auto_any/browsergate/profile_clone.py +134 -0
  14. auto_any/browsergate/profile_port.py +28 -0
  15. auto_any/browsergate/profile_selection.py +273 -0
  16. auto_any/browsergate/registry.py +11 -0
  17. auto_any/browsergate/selection.py +49 -0
  18. auto_any/browsergate/selenium_driver.py +135 -0
  19. auto_any/browsergate/session.py +38 -0
  20. auto_any/browsergate/vision_port.py +30 -0
  21. auto_any/build_info.py +81 -0
  22. auto_any/capabilities/__init__.py +6 -0
  23. auto_any/capabilities/base.py +45 -0
  24. auto_any/capabilities/browser.py +20 -0
  25. auto_any/capabilities/extract.py +38 -0
  26. auto_any/capabilities/gate.py +281 -0
  27. auto_any/capabilities/http.py +14 -0
  28. auto_any/capabilities/registry.py +10 -0
  29. auto_any/capabilities/shell.py +14 -0
  30. auto_any/capabilities/verify.py +33 -0
  31. auto_any/cli.py +261 -0
  32. auto_any/conductor/__init__.py +1 -0
  33. auto_any/conductor/budget.py +29 -0
  34. auto_any/conductor/conductor.py +10 -0
  35. auto_any/conductor/prompts/act.md +21 -0
  36. auto_any/conductor/prompts/fragments/act/auth_flow.md +1 -0
  37. auto_any/conductor/prompts/fragments/act/extraction.md +1 -0
  38. auto_any/conductor/prompts/fragments/act/form_fill.md +1 -0
  39. auto_any/conductor/prompts/fragments/act/navigation.md +1 -0
  40. auto_any/conductor/prompts/fragments/act/pagination.md +1 -0
  41. auto_any/conductor/prompts/fragments/act/verification.md +1 -0
  42. auto_any/conductor/prompts/fragments/plan/auth_flow.md +1 -0
  43. auto_any/conductor/prompts/fragments/plan/extraction.md +1 -0
  44. auto_any/conductor/prompts/fragments/plan/form_fill.md +1 -0
  45. auto_any/conductor/prompts/fragments/plan/navigation.md +1 -0
  46. auto_any/conductor/prompts/fragments/plan/pagination.md +1 -0
  47. auto_any/conductor/prompts/fragments/plan/verification.md +1 -0
  48. auto_any/conductor/prompts/plan.md +1 -0
  49. auto_any/conductor/shield.py +31 -0
  50. auto_any/config.py +109 -0
  51. auto_any/engine/__init__.py +11 -0
  52. auto_any/engine/base.py +17 -0
  53. auto_any/engine/llm.py +142 -0
  54. auto_any/engine/local.py +262 -0
  55. auto_any/engine/remote.py +30 -0
  56. auto_any/main.py +39 -0
  57. auto_any/mcp_server.py +282 -0
  58. auto_any/memory/__init__.py +0 -0
  59. auto_any/memory/site_profiles.py +213 -0
  60. auto_any/packs/__init__.py +17 -0
  61. auto_any/packs/base.py +88 -0
  62. auto_any/packs/builtin/__init__.py +16 -0
  63. auto_any/packs/builtin/form_fill.py +37 -0
  64. auto_any/packs/builtin/linkedin_apply.py +47 -0
  65. auto_any/packs/builtin/login_download.py +41 -0
  66. auto_any/packs/builtin/scrape_table.py +34 -0
  67. auto_any/packs/builtin/smoke_test.py +35 -0
  68. auto_any/packs/compile.py +34 -0
  69. auto_any/packs/discovery.py +82 -0
  70. auto_any/packs/registry.py +36 -0
  71. auto_any/replay/__init__.py +4 -0
  72. auto_any/replay/distiller.py +98 -0
  73. auto_any/replay/ledger.py +178 -0
  74. auto_any/replay/service.py +28 -0
  75. auto_any/replay/signature.py +15 -0
  76. auto_any/replay/store.py +20 -0
  77. auto_any/runtime/__init__.py +1 -0
  78. auto_any/runtime/container.py +82 -0
  79. auto_any/schemas.py +31 -0
  80. auto_any/security.py +58 -0
  81. auto_any/state/__init__.py +1 -0
  82. auto_any/state/pending.py +44 -0
  83. auto_any/taperoom/__init__.py +41 -0
  84. auto_any/telemetry.py +15 -0
  85. auto_any/vendors/__init__.py +1 -0
  86. auto_any/vendors/contracts.py +33 -0
  87. auto_any/vendors/efa.py +114 -0
  88. auto_any/vendors/exporter.py +161 -0
  89. auto_any/vendors/scorer.py +184 -0
  90. auto_any-0.1.0.dist-info/METADATA +289 -0
  91. auto_any-0.1.0.dist-info/RECORD +146 -0
  92. auto_any-0.1.0.dist-info/WHEEL +4 -0
  93. auto_any-0.1.0.dist-info/entry_points.txt +3 -0
  94. replayable_test_runner/__init__.py +3 -0
  95. replayable_test_runner/abstractions/__init__.py +53 -0
  96. replayable_test_runner/abstractions/checkout.py +22 -0
  97. replayable_test_runner/abstractions/embedding.py +25 -0
  98. replayable_test_runner/abstractions/executor.py +29 -0
  99. replayable_test_runner/abstractions/llm.py +55 -0
  100. replayable_test_runner/abstractions/planner.py +21 -0
  101. replayable_test_runner/abstractions/pr_source.py +29 -0
  102. replayable_test_runner/abstractions/reporter.py +19 -0
  103. replayable_test_runner/abstractions/reviewer.py +22 -0
  104. replayable_test_runner/abstractions/runner.py +51 -0
  105. replayable_test_runner/abstractions/signature.py +16 -0
  106. replayable_test_runner/abstractions/store.py +56 -0
  107. replayable_test_runner/cli.py +128 -0
  108. replayable_test_runner/domain/__init__.py +33 -0
  109. replayable_test_runner/domain/pr.py +32 -0
  110. replayable_test_runner/domain/receipt.py +95 -0
  111. replayable_test_runner/domain/results.py +51 -0
  112. replayable_test_runner/domain/review.py +35 -0
  113. replayable_test_runner/domain/signature.py +21 -0
  114. replayable_test_runner/infra/__init__.py +5 -0
  115. replayable_test_runner/infra/checkout_git.py +48 -0
  116. replayable_test_runner/infra/fs_safety.py +168 -0
  117. replayable_test_runner/infra/pr_github.py +91 -0
  118. replayable_test_runner/infra/signatures.py +73 -0
  119. replayable_test_runner/infra/state_json.py +130 -0
  120. replayable_test_runner/infra/store_json.py +112 -0
  121. replayable_test_runner/infra/vcs.py +34 -0
  122. replayable_test_runner/pipeline/__init__.py +1 -0
  123. replayable_test_runner/pipeline/assertions.py +264 -0
  124. replayable_test_runner/pipeline/container.py +91 -0
  125. replayable_test_runner/pipeline/executor.py +83 -0
  126. replayable_test_runner/pipeline/planner.py +281 -0
  127. replayable_test_runner/pipeline/prompts.py +56 -0
  128. replayable_test_runner/pipeline/repair.py +243 -0
  129. replayable_test_runner/pipeline/reporter.py +77 -0
  130. replayable_test_runner/pipeline/reviewer.py +252 -0
  131. replayable_test_runner/pipeline/runner.py +296 -0
  132. replayable_test_runner/providers/__init__.py +8 -0
  133. replayable_test_runner/providers/embedders.py +75 -0
  134. replayable_test_runner/providers/llm.py +285 -0
  135. replayable_test_runner/runners/__init__.py +11 -0
  136. replayable_test_runner/runners/http.py +522 -0
  137. replayable_test_runner/runners/http_probe.py +138 -0
  138. replayable_test_runner/runners/playwright.py +76 -0
  139. replayable_test_runner/runners/playwright_chromium.py +308 -0
  140. replayable_test_runner/runners/shell.py +423 -0
  141. replayable_test_runner/settings.py +58 -0
  142. replayable_test_runner/support/__init__.py +1 -0
  143. replayable_test_runner/support/errors.py +23 -0
  144. replayable_test_runner/support/logging.py +28 -0
  145. replayable_test_runner/support/net.py +139 -0
  146. replayable_test_runner/support/registry.py +45 -0
auto_any/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """auto_any — a general task engine with a pluggable pack extension surface.
2
+
3
+ Public platform API: subclass `Playbook`, set a `PlaybookSpec`, and `register`
4
+ it (or ship it as an ``auto_any.packs`` entry point) to add a new use-case —
5
+ LinkedIn apply, app testing, scraping, any UI automation — with zero core edits.
6
+ """
7
+
8
+ from .packs import Playbook, PlaybookRun, PlaybookSpec, register
9
+
10
+ __version__ = "0.1.0"
11
+ __all__ = ["Playbook", "PlaybookRun", "PlaybookSpec", "register", "__version__"]
@@ -0,0 +1 @@
1
+ """HTTP API routers."""
@@ -0,0 +1,209 @@
1
+ import json
2
+ import uuid
3
+ from fastapi import APIRouter, Depends
4
+ from sse_starlette.sse import EventSourceResponse
5
+ from ..security import Caller, bearer_auth
6
+ from ..schemas import AutomationRequest, ResumeRequest
7
+ from ..runtime.container import runtime
8
+ from ..replay.signature import build_signature
9
+ from ..conductor.shield import OutputShield
10
+ from ..browsergate.selection import build_driver, select_driver_name
11
+ from ..memory.site_profiles import SiteProfileMemory, netloc_for_url, profile_name_for_url
12
+ from ..vendors.scorer import RunContext, SCORERS
13
+
14
+ router = APIRouter()
15
+
16
+
17
+ @router.post("/automations/{run_id}/resume")
18
+ async def resume(run_id: str, req: ResumeRequest, _: Caller = Depends(bearer_auth), rt=Depends(runtime)):
19
+ async def events():
20
+ if not getattr(rt.engine, "pending", None) or rt.engine.pending.get(run_id) is None:
21
+ yield {
22
+ "event": "message",
23
+ "data": json.dumps({"kind": "error", "status": 404, "error": "pending run not found"}),
24
+ }
25
+ return
26
+ async for event in rt.engine.resume(run_id, req.value):
27
+ yield {"event": "message", "data": json.dumps(OutputShield().filter_event(event))}
28
+
29
+ return EventSourceResponse(events())
30
+
31
+
32
+ @router.post("/automations")
33
+ async def automate(req: AutomationRequest, caller: Caller = Depends(bearer_auth), rt=Depends(runtime)):
34
+ return EventSourceResponse(automation_events(rt, caller, req))
35
+
36
+
37
+ async def automation_events(rt, caller: Caller, req: AutomationRequest):
38
+ """Shared SSE run generator used by /automations and /packs/{name}/run."""
39
+
40
+ async def events():
41
+ run_id = str(uuid.uuid4())
42
+ sig = build_signature(req.goal, req.url, req.context)
43
+ receipt, route = await rt.replay.lookup(sig) if req.mode != "always_plan" else (None, "miss")
44
+ yield {
45
+ "event": "message",
46
+ "data": json.dumps(
47
+ {
48
+ "kind": "run_started",
49
+ "run_id": run_id,
50
+ "signature_key": sig.key,
51
+ "route": "replay" if receipt else "agentic",
52
+ }
53
+ ),
54
+ }
55
+ if req.mode == "replay_only" and not receipt:
56
+ yield {
57
+ "event": "message",
58
+ "data": json.dumps({"kind": "run_finished", "status": "failed", "error": "receipt not found"}),
59
+ }
60
+ return
61
+ from pathlib import Path
62
+
63
+ step_count = 0
64
+ artifacts: list[str] = []
65
+ if receipt:
66
+ result = await rt.replay.replay(receipt, Path(rt.cfg.artifacts_dir), receipt.url or req.url)
67
+ for step in result.steps:
68
+ step_count += 1
69
+ yield {
70
+ "event": "message",
71
+ "data": json.dumps(
72
+ {
73
+ "kind": "replay_step",
74
+ "step_id": step.step_id,
75
+ "status": "passed" if step.passed else "failed",
76
+ }
77
+ ),
78
+ }
79
+ status = "succeeded" if result.passed else "failed"
80
+ yield {"event": "message", "data": json.dumps({"kind": "run_finished", "status": status, "artifacts": []})}
81
+ else:
82
+ # The engine emits its OWN run_finished (succeeded | failed | max_steps);
83
+ # capture that status here rather than fabricating a second event.
84
+ status = "failed"
85
+ effective_mode = (req.profile or {}).get("mode", rt.cfg.profile_mode)
86
+ memory = None
87
+ remember_profile_name = None
88
+ resolved_profile = req.profile
89
+ try:
90
+ if effective_mode == "remember":
91
+ memory = SiteProfileMemory(rt.cfg)
92
+ hint = memory.lookup(req.url)
93
+ base_profile_fields = {
94
+ "chrome_user_data": rt.cfg.chrome_user_data,
95
+ "source_profile": rt.cfg.chrome_source_profile,
96
+ "profiles_dir": rt.cfg.profiles_dir,
97
+ "channel": rt.cfg.chrome_channel,
98
+ }
99
+ if hint:
100
+ resolved_profile = {"mode": "named", "name": hint["profile_name"], **base_profile_fields}
101
+ else:
102
+ remember_profile_name = profile_name_for_url(req.url)
103
+ resolved_profile = {"mode": "clone", **base_profile_fields}
104
+ original_driver = getattr(rt.gate, "_driver", None)
105
+ created_per_run_driver = False
106
+ name = select_driver_name(
107
+ rt.cfg,
108
+ request_override=req.driver,
109
+ pack_hint=req.context.get("_driver"),
110
+ task_hint=req.context.get("task_hint"),
111
+ )
112
+ driver = build_driver(rt.cfg, name, rt.gate.policy, run_id=run_id)
113
+ rt.gate.set_driver(driver)
114
+ created_per_run_driver = True
115
+ await rt.gate.open(req.url, run_id=run_id, profile=resolved_profile)
116
+ except Exception as exc: # noqa: BLE001 — vendor availability is a run failure, not an API crash
117
+ yield {"event": "message", "data": json.dumps({"kind": "run_finished", "status": "failed", "error": str(exc)})}
118
+ return
119
+ async for event in rt.engine.run_turn(
120
+ thread_id=run_id, text=req.goal, token=caller.token, signature_key=sig.key, context=req.context, url=req.url
121
+ ):
122
+ if event.get("kind") == "run_finished":
123
+ status = event.get("status", status)
124
+ artifacts = event.get("artifacts", []) or getattr(rt.gate, "artifacts", lambda: [])()
125
+ event = {**event, "artifacts": artifacts}
126
+ if event.get("kind") == "receipt_saved":
127
+ # The receipt was distilled from the executed trace; use its
128
+ # step count as the single source of truth so the ledger row
129
+ # always describes what the receipt contains.
130
+ step_count = event.get("steps", step_count)
131
+ elif event.get("kind") in {"progress", "replay_step"} or "action" in event:
132
+ step_count += 1
133
+ yield {"event": "message", "data": json.dumps(OutputShield().filter_event(event))}
134
+ await rt.gate.dispose_profile()
135
+ if effective_mode == "remember" and memory is not None:
136
+ site = netloc_for_url(req.url)
137
+ if status == "succeeded" and remember_profile_name:
138
+ memory.remember(req.url, profile_name=remember_profile_name)
139
+ yield {
140
+ "event": "message",
141
+ "data": json.dumps(
142
+ OutputShield().filter_event(
143
+ {
144
+ "kind": "profile_remembered",
145
+ "site": site,
146
+ "profile": remember_profile_name,
147
+ "note": memory.to_note(req.url),
148
+ }
149
+ )
150
+ ),
151
+ }
152
+ elif status != "succeeded":
153
+ if remember_profile_name:
154
+ yield {
155
+ "event": "message",
156
+ "data": json.dumps(
157
+ OutputShield().filter_event(
158
+ {
159
+ "kind": "login_failed",
160
+ "site": site,
161
+ "hint": "profile cloned but login not confirmed",
162
+ }
163
+ )
164
+ ),
165
+ }
166
+ elif memory.lookup(req.url) is not None:
167
+ memory.forget(req.url)
168
+ yield {
169
+ "event": "message",
170
+ "data": json.dumps(
171
+ OutputShield().filter_event({"kind": "profile_stale", "site": site})
172
+ ),
173
+ }
174
+
175
+ if created_per_run_driver:
176
+ await rt.gate.close()
177
+ rt.gate.set_driver(original_driver)
178
+
179
+ scorer_name = req.score or getattr(rt.cfg, "scorer", "null")
180
+ if scorer_name and scorer_name != "null":
181
+ try:
182
+ scorer = SCORERS.create(scorer_name)
183
+ report = await scorer.score(RunContext(
184
+ artifacts_dir=artifacts[0] if artifacts else getattr(rt.cfg, "artifacts_dir", ""),
185
+ url=req.url, status=status, run_id=run_id,
186
+ ))
187
+ yield {"event": "message", "data": json.dumps({"kind": "score_report", **report.__dict__})}
188
+ except Exception as exc: # noqa: BLE001 — vendor scoring cannot fail a run
189
+ yield {"event": "message", "data": json.dumps({"kind": "score_report", "ok": False, "scores": {}, "summary": str(exc)})}
190
+
191
+ await _record(rt, run_id, req, sig.key, "replay" if receipt else "agentic", step_count, status, artifacts)
192
+
193
+ async for event in events():
194
+ yield event
195
+
196
+
197
+ async def _record(rt, run_id, req, signature_key, route, step_count, status, artifacts):
198
+ """Best-effort ledger write — a ledger outage never breaks the response."""
199
+ ledger = getattr(rt, "ledger", None)
200
+ if ledger is None:
201
+ return
202
+ from ..replay.ledger import record_for
203
+
204
+ rec = record_for(run_id, req.goal, signature_key, route, step_count, status,
205
+ artifacts_dir=artifacts[0] if artifacts else "")
206
+ try:
207
+ await ledger.record(rec)
208
+ except Exception: # noqa: BLE001 — ledger must never fail the run
209
+ pass
auto_any/api/packs.py ADDED
@@ -0,0 +1,56 @@
1
+ """Pack API — list installed playbooks and run one from typed params."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from fastapi import APIRouter, Depends
9
+ from sse_starlette.sse import EventSourceResponse
10
+
11
+ from ..packs import all_packs, get, has
12
+ from ..packs.compile import to_request
13
+ from ..runtime.container import runtime
14
+ from ..security import Caller, bearer_auth
15
+ from .automations import automation_events
16
+
17
+ router = APIRouter()
18
+
19
+
20
+ @router.get("/packs")
21
+ async def list_packs(_: Caller = Depends(bearer_auth)) -> list[dict[str, Any]]:
22
+ """List installed playbooks with their typed parameter schemas."""
23
+ return [
24
+ {
25
+ "name": pb.spec.name,
26
+ "description": pb.spec.description,
27
+ "params_schema": pb.spec.params_schema,
28
+ "capabilities": pb.spec.capabilities,
29
+ "profile_name": pb.spec.profile_name,
30
+ }
31
+ for pb in all_packs()
32
+ ]
33
+
34
+
35
+ @router.post("/packs/{name}/run")
36
+ async def run_pack(
37
+ name: str,
38
+ params: dict[str, Any],
39
+ caller: Caller = Depends(bearer_auth),
40
+ rt=Depends(runtime),
41
+ ):
42
+ """Run a playbook: validate params, compile to a request, stream the run."""
43
+
44
+ async def events():
45
+ if not has(name):
46
+ yield {"event": "message", "data": json.dumps({"kind": "error", "status": 404, "error": f"no pack {name!r}"})}
47
+ return
48
+ try:
49
+ req = to_request(get(name), params)
50
+ except ValueError as exc:
51
+ yield {"event": "message", "data": json.dumps({"kind": "error", "status": 422, "error": str(exc)})}
52
+ return
53
+ async for event in automation_events(rt, caller, req):
54
+ yield event
55
+
56
+ return EventSourceResponse(events())
@@ -0,0 +1,18 @@
1
+ from fastapi import APIRouter, Depends, HTTPException
2
+ from ..security import Caller, bearer_auth
3
+ from ..runtime.container import runtime
4
+
5
+ router = APIRouter()
6
+
7
+
8
+ @router.get("/profiles")
9
+ async def profiles(_: Caller = Depends(bearer_auth), rt=Depends(runtime)):
10
+ return rt.profile_port.list_named() if hasattr(rt, "profile_port") and rt.profile_port else []
11
+
12
+
13
+ @router.delete("/profiles/{name}")
14
+ async def delete_profile(name: str, _: Caller = Depends(bearer_auth), rt=Depends(runtime)):
15
+ port = getattr(rt, "profile_port", None)
16
+ if not port or not port.delete_named(name):
17
+ raise HTTPException(404, "profile not found")
18
+ return {"deleted": name}
@@ -0,0 +1,38 @@
1
+ from fastapi import APIRouter, Depends, HTTPException
2
+ from ..security import Caller, bearer_auth
3
+ from ..runtime.container import runtime
4
+ from ..vendors.exporter import EXPORTERS
5
+
6
+ router = APIRouter(prefix="/receipts")
7
+
8
+
9
+ @router.get("")
10
+ async def all_receipts(_: Caller = Depends(bearer_auth), rt=Depends(runtime)):
11
+ return await rt.receipts.all()
12
+
13
+
14
+ @router.get("/{key}")
15
+ async def get_receipt(key: str, _: Caller = Depends(bearer_auth), rt=Depends(runtime)):
16
+ receipt = await rt.receipts.get_exact(key)
17
+ if not receipt:
18
+ raise HTTPException(404, "receipt not found")
19
+ return receipt
20
+
21
+
22
+ @router.delete("/{key}")
23
+ async def delete_receipt(key: str, _: Caller = Depends(bearer_auth), rt=Depends(runtime)):
24
+ return {"deleted": await rt.receipts.delete(key)}
25
+
26
+
27
+ @router.post("/{key}/export")
28
+ async def export_receipt(key: str, body: dict, _: Caller = Depends(bearer_auth), rt=Depends(runtime)):
29
+ """Export a receipt offline into a vendor-native test specification."""
30
+ format_name = body.get("format")
31
+ if format_name not in EXPORTERS.names():
32
+ raise HTTPException(400, f"unknown export format: {format_name}")
33
+ receipt = await rt.receipts.get_exact(key)
34
+ if not receipt:
35
+ raise HTTPException(404, "receipt not found")
36
+ exporter = EXPORTERS.create(format_name)
37
+ content = exporter.export(receipt)
38
+ return {"filename": f"{key}{exporter.extension}", "content": content}
@@ -0,0 +1,27 @@
1
+ from .base import BrowserDriver, DriverUnavailable, Observation
2
+ from .appium_driver import AppiumDriver
3
+ from .selenium_driver import SeleniumDriver
4
+ from .profile_selection import (
5
+ ProfileStrategy,
6
+ ProfileSelectionError,
7
+ ProfileLockError,
8
+ ProfileUnavailableError,
9
+ ProfileSelectionResult,
10
+ select_profile_strategy,
11
+ prepare_profile_for_mode,
12
+ )
13
+
14
+ __all__ = [
15
+ "AppiumDriver",
16
+ "BrowserDriver",
17
+ "DriverUnavailable",
18
+ "Observation",
19
+ "SeleniumDriver",
20
+ "ProfileStrategy",
21
+ "ProfileSelectionError",
22
+ "ProfileLockError",
23
+ "ProfileUnavailableError",
24
+ "ProfileSelectionResult",
25
+ "select_profile_strategy",
26
+ "prepare_profile_for_mode",
27
+ ]
@@ -0,0 +1,82 @@
1
+ """Lazy Appium mobile driver."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from typing import Any
7
+
8
+ from .base import BrowserDriver, DriverUnavailable, Observation
9
+
10
+
11
+ class AppiumDriver(BrowserDriver):
12
+ """Drive a mobile UI through an Appium server."""
13
+
14
+ def __init__(self, server_url: str, capabilities: dict[str, Any] | None = None, policy=None):
15
+ self.server_url, self.capabilities, self.policy = server_url, capabilities or {}, policy
16
+ self.driver = None
17
+
18
+ async def open(self, url: str, profile=None) -> Observation:
19
+ if self.policy:
20
+ self.policy.check(url)
21
+
22
+ def start() -> Any:
23
+ try:
24
+ from appium import webdriver
25
+ except ImportError as exc:
26
+ raise DriverUnavailable("appium client + running Appium server at AANY_APPIUM_URL required") from exc
27
+ try:
28
+ return webdriver.Remote(self.server_url, options=self.capabilities)
29
+ except Exception as exc:
30
+ raise DriverUnavailable(
31
+ "appium client + running Appium server at AANY_APPIUM_URL required"
32
+ ) from exc
33
+
34
+ self.driver = await asyncio.to_thread(start)
35
+ if url:
36
+ await asyncio.to_thread(self.driver.get, url)
37
+ return await self.snapshot()
38
+
39
+ async def close(self) -> None:
40
+ if self.driver:
41
+ await asyncio.to_thread(self.driver.quit)
42
+ self.driver = None
43
+
44
+ async def snapshot(self) -> Observation:
45
+ if not self.driver:
46
+ return Observation("", snapshot_excerpt="driver is not open")
47
+ return Observation(str(self.driver.current_url), str(self.driver.title), str(self.driver.page_source)[:12000])
48
+
49
+ def _element(self, selector: str):
50
+ from appium.webdriver.common.appiumby import AppiumBy
51
+
52
+ if selector.startswith("accessibility_id="):
53
+ return self.driver.find_element(AppiumBy.ACCESSIBILITY_ID, selector.split("=", 1)[1])
54
+ return self.driver.find_element(AppiumBy.XPATH, selector.removeprefix("xpath="))
55
+
56
+ async def click(self, selector: str) -> Observation:
57
+ await asyncio.to_thread(lambda: self._element(selector).click())
58
+ return await self.snapshot()
59
+
60
+ async def type(self, selector: str, text: str, secret: bool = False) -> Observation:
61
+ await asyncio.to_thread(lambda: self._element(selector).send_keys(text))
62
+ return await self.snapshot()
63
+
64
+ async def select(self, selector: str, value: str) -> Observation:
65
+ await asyncio.to_thread(lambda: self._element(selector).send_keys(value))
66
+ return await self.snapshot()
67
+
68
+ async def press(self, key: str) -> Observation:
69
+ await asyncio.to_thread(self.driver.press_keycode, int(key) if key.isdigit() else key)
70
+ return await self.snapshot()
71
+
72
+ async def wait_for(self, selector=None, url=None, timeout=None) -> Observation:
73
+ if selector:
74
+ await asyncio.to_thread(self._element(selector))
75
+ return await self.snapshot()
76
+
77
+ async def evaluate(self, js: str) -> Any:
78
+ return await asyncio.to_thread(self.driver.execute_script, js)
79
+
80
+ async def screenshot(self, name: str) -> str:
81
+ await asyncio.to_thread(self.driver.save_screenshot, name)
82
+ return name
@@ -0,0 +1,45 @@
1
+ from abc import ABC, abstractmethod
2
+ from dataclasses import dataclass, field
3
+ from typing import Any
4
+ from replayable_test_runner.abstractions.runner import DriverUnavailable
5
+
6
+ __all__ = ["BrowserDriver", "DriverUnavailable", "Observation"]
7
+
8
+
9
+ @dataclass
10
+ class Observation:
11
+ url: str
12
+ title: str = ""
13
+ snapshot_excerpt: str = ""
14
+ console_errors: list[str] = field(default_factory=list)
15
+
16
+
17
+ class BrowserDriver(ABC):
18
+ @abstractmethod
19
+ async def open(self, url: str) -> Observation: ...
20
+ @abstractmethod
21
+ async def close(self) -> None: ...
22
+ @abstractmethod
23
+ async def snapshot(self) -> Observation: ...
24
+ async def screenshot(self, name: str) -> str:
25
+ raise NotImplementedError
26
+
27
+ async def click(self, selector: str) -> Observation:
28
+ raise NotImplementedError
29
+
30
+ async def type(self, selector: str, text: str, secret: bool = False) -> Observation:
31
+ raise NotImplementedError
32
+
33
+ async def select(self, selector: str, value: str) -> Observation:
34
+ raise NotImplementedError
35
+
36
+ async def press(self, key: str) -> Observation:
37
+ raise NotImplementedError
38
+
39
+ async def wait_for(
40
+ self, selector: str | None = None, url: str | None = None, timeout: float | None = None
41
+ ) -> Observation:
42
+ raise NotImplementedError
43
+
44
+ async def evaluate(self, js: str) -> Any:
45
+ raise NotImplementedError
@@ -0,0 +1,158 @@
1
+ from datetime import datetime
2
+ import logging
3
+ from pathlib import Path
4
+ from .base import BrowserDriver, DriverUnavailable, Observation
5
+ from .profile_port import PreparedProfile
6
+
7
+ log = logging.getLogger(__name__)
8
+
9
+
10
+ class PlaywrightDriver(BrowserDriver):
11
+ """Per-run Playwright driver; import is intentionally lazy."""
12
+
13
+ def __init__(
14
+ self,
15
+ headless: bool = True,
16
+ artifacts_dir: str = "./artifacts",
17
+ policy=None,
18
+ trace: bool = True,
19
+ video: bool = False,
20
+ run_id: str | None = None,
21
+ auto_screenshot: bool = True,
22
+ ):
23
+ self.headless = headless
24
+ self.artifacts_dir = Path(artifacts_dir)
25
+ self.policy = policy
26
+ self.trace, self.video = trace, video
27
+ self.run_id = run_id
28
+ self.auto_screenshot = auto_screenshot
29
+ self._step_count = 0
30
+ self._run_dir: Path | None = None
31
+ self.page = None
32
+ self.context = None
33
+ self._pw = None
34
+
35
+ @property
36
+ def run_dir(self) -> Path:
37
+ """Public accessor for the per-run artifacts directory."""
38
+ return self._ensure_run_dir()
39
+
40
+ def _ensure_run_dir(self) -> Path:
41
+ """Ensure per-run directory exists, creating it if necessary."""
42
+ if self._run_dir is None:
43
+ if self.run_id:
44
+ self._run_dir = self.artifacts_dir / self.run_id
45
+ else:
46
+ self._run_dir = self.artifacts_dir / datetime.now().strftime("%Y%m%d_%H%M%S_%f")
47
+ self._run_dir.mkdir(parents=True, exist_ok=True)
48
+ return self._run_dir
49
+
50
+ async def _auto_capture(self, action_name: str) -> None:
51
+ """Capture a screenshot after each action, non-fatal on failure."""
52
+ if not self.auto_screenshot or self.page is None:
53
+ return
54
+ self._step_count += 1
55
+ try:
56
+ run_dir = self._ensure_run_dir()
57
+ filename = f"{self._step_count:03d}_{action_name}.png"
58
+ path = run_dir / filename
59
+ await self.page.screenshot(path=str(path))
60
+ log.debug("auto-captured %s", path)
61
+ except Exception as exc:
62
+ log.warning("auto-screenshot failed for %s: %s", action_name, exc)
63
+
64
+ async def open(self, url, profile: PreparedProfile | None = None):
65
+ try:
66
+ from playwright.async_api import async_playwright
67
+ except ImportError as exc:
68
+ raise DriverUnavailable("pip install auto-any[browser] and run playwright install") from exc
69
+
70
+ # Ensure run_dir is created early for trace/video
71
+ run_dir = self._ensure_run_dir()
72
+
73
+ if self.policy:
74
+ self.policy.check(url)
75
+ self._pw = await async_playwright().start()
76
+ cdp_url = getattr(profile, "cdp_url", "") if profile is not None else ""
77
+ if cdp_url:
78
+ browser = await self._pw.chromium.connect_over_cdp(cdp_url)
79
+ self.browser = None
80
+ if not browser.contexts:
81
+ raise RuntimeError("CDP browser has no available browser context")
82
+ self.context = browser.contexts[0]
83
+ elif profile is not None:
84
+ self.context = await self._pw.chromium.launch_persistent_context(
85
+ user_data_dir=str(profile.user_data_dir),
86
+ channel=profile.channel or "chrome",
87
+ headless=self.headless,
88
+ record_video_dir=str(run_dir) if self.video else None,
89
+ args=[f"--profile-directory={profile.profile_dir}"] if profile.profile_dir != "Default" else [],
90
+ )
91
+ self.browser = None
92
+ else:
93
+ self.browser = await self._pw.chromium.launch(headless=self.headless)
94
+ self.context = await self.browser.new_context(
95
+ record_video_dir=str(run_dir) if self.video else None
96
+ )
97
+ if self.trace:
98
+ await self.context.tracing.start(screenshots=True, snapshots=True, sources=True)
99
+ self.page = await self.context.new_page()
100
+ await self.page.goto(url)
101
+ await self._auto_capture("open")
102
+ return await self.snapshot()
103
+
104
+ async def close(self):
105
+ if self.context:
106
+ if self.trace:
107
+ try:
108
+ run_dir = self._ensure_run_dir()
109
+ await self.context.tracing.stop(path=str(run_dir / "trace.zip"))
110
+ except OSError:
111
+ pass
112
+ await self.context.close()
113
+ if getattr(self, "browser", None):
114
+ await self.browser.close()
115
+ if self._pw:
116
+ await self._pw.stop()
117
+
118
+ async def snapshot(self):
119
+ return Observation(
120
+ self.page.url, await self.page.title(), (await self.page.locator("body").inner_text())[:12000]
121
+ )
122
+
123
+ async def click(self, selector):
124
+ await self.page.click(selector)
125
+ await self._auto_capture("click")
126
+ return await self.snapshot()
127
+
128
+ async def type(self, selector, text, secret=False):
129
+ await self.page.fill(selector, text)
130
+ await self._auto_capture("type")
131
+ return await self.snapshot()
132
+
133
+ async def select(self, selector, value):
134
+ await self.page.select_option(selector, value)
135
+ await self._auto_capture("select")
136
+ return await self.snapshot()
137
+
138
+ async def press(self, key):
139
+ await self.page.keyboard.press(key)
140
+ await self._auto_capture("press_key")
141
+ return await self.snapshot()
142
+
143
+ async def wait_for(self, selector=None, url=None, timeout=None):
144
+ if selector:
145
+ await self.page.wait_for_selector(selector, timeout=timeout)
146
+ elif url:
147
+ await self.page.wait_for_url(url, timeout=timeout)
148
+ await self._auto_capture("wait_for")
149
+ return await self.snapshot()
150
+
151
+ async def evaluate(self, js):
152
+ return await self.page.evaluate(js)
153
+
154
+ async def screenshot(self, name):
155
+ run_dir = self._ensure_run_dir()
156
+ path = run_dir / name
157
+ await self.page.screenshot(path=str(path))
158
+ return str(path)