manul-browser 0.1.2__py3-none-win_arm64.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.
- manul/__init__.py +104 -0
- manul/__main__.py +10 -0
- manul/_bin/manul.exe +0 -0
- manul/_binary.py +88 -0
- manul/_cli.py +60 -0
- manul/_hookhost.py +153 -0
- manul/_transport.py +277 -0
- manul/controls.py +446 -0
- manul/errors.py +56 -0
- manul/py.typed +0 -0
- manul/session.py +429 -0
- manul_browser-0.1.2.dist-info/METADATA +262 -0
- manul_browser-0.1.2.dist-info/RECORD +16 -0
- manul_browser-0.1.2.dist-info/WHEEL +4 -0
- manul_browser-0.1.2.dist-info/entry_points.txt +2 -0
- manul_browser-0.1.2.dist-info/licenses/LICENSE +201 -0
manul/__init__.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Manul — browser automation in plain English, for humans and LLM agents.
|
|
2
|
+
|
|
3
|
+
This package is a thin client for the Manul engine. It ships the engine binary,
|
|
4
|
+
starts it, and speaks a JSON protocol to it; the scoring, the .hunt DSL and the
|
|
5
|
+
CDP transport all live in the engine itself, in exactly one implementation.
|
|
6
|
+
|
|
7
|
+
import manul
|
|
8
|
+
|
|
9
|
+
with manul.Session() as s:
|
|
10
|
+
s.step("NAVIGATE to https://example.com")
|
|
11
|
+
s.step("CLICK the 'Sign in' button")
|
|
12
|
+
print(s.map().labels())
|
|
13
|
+
|
|
14
|
+
To drive a Chrome you already have open, launched with
|
|
15
|
+
``--remote-debugging-port=9222``::
|
|
16
|
+
|
|
17
|
+
with manul.Session(mode="attach") as s:
|
|
18
|
+
print(s.state()["url"])
|
|
19
|
+
|
|
20
|
+
That browser stays open when the session ends — Manul did not open it.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from ._binary import find_binary
|
|
26
|
+
from ._hookhost import serve_hooks
|
|
27
|
+
from ._transport import Transport
|
|
28
|
+
from .controls import (
|
|
29
|
+
ANY_PAGE,
|
|
30
|
+
GlobalContext,
|
|
31
|
+
after_all,
|
|
32
|
+
after_group,
|
|
33
|
+
before_all,
|
|
34
|
+
before_group,
|
|
35
|
+
list_hooks,
|
|
36
|
+
CallContext,
|
|
37
|
+
ControlContext,
|
|
38
|
+
call,
|
|
39
|
+
custom_control,
|
|
40
|
+
diagnose_custom_control_miss,
|
|
41
|
+
get_call,
|
|
42
|
+
get_custom_control,
|
|
43
|
+
list_calls,
|
|
44
|
+
list_custom_controls,
|
|
45
|
+
reset_registry,
|
|
46
|
+
)
|
|
47
|
+
from .errors import (
|
|
48
|
+
EngineError,
|
|
49
|
+
EngineNotFound,
|
|
50
|
+
ManulError,
|
|
51
|
+
ProtocolError,
|
|
52
|
+
SessionClosed,
|
|
53
|
+
)
|
|
54
|
+
from .session import (
|
|
55
|
+
MapElement,
|
|
56
|
+
SuiteHunt,
|
|
57
|
+
SuiteResult,
|
|
58
|
+
MapGroup,
|
|
59
|
+
PageMap,
|
|
60
|
+
RunOutcome,
|
|
61
|
+
Session,
|
|
62
|
+
StepOutcome,
|
|
63
|
+
Value,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
__version__ = "0.1.2"
|
|
67
|
+
|
|
68
|
+
__all__ = [
|
|
69
|
+
"Session",
|
|
70
|
+
"StepOutcome",
|
|
71
|
+
"RunOutcome",
|
|
72
|
+
"PageMap",
|
|
73
|
+
"MapGroup",
|
|
74
|
+
"MapElement",
|
|
75
|
+
"Value",
|
|
76
|
+
"custom_control",
|
|
77
|
+
"call",
|
|
78
|
+
"ControlContext",
|
|
79
|
+
"CallContext",
|
|
80
|
+
"get_custom_control",
|
|
81
|
+
"get_call",
|
|
82
|
+
"list_custom_controls",
|
|
83
|
+
"list_calls",
|
|
84
|
+
"diagnose_custom_control_miss",
|
|
85
|
+
"reset_registry",
|
|
86
|
+
"ANY_PAGE",
|
|
87
|
+
"before_all",
|
|
88
|
+
"after_all",
|
|
89
|
+
"before_group",
|
|
90
|
+
"after_group",
|
|
91
|
+
"GlobalContext",
|
|
92
|
+
"list_hooks",
|
|
93
|
+
"serve_hooks",
|
|
94
|
+
"SuiteResult",
|
|
95
|
+
"SuiteHunt",
|
|
96
|
+
"ManulError",
|
|
97
|
+
"EngineNotFound",
|
|
98
|
+
"ProtocolError",
|
|
99
|
+
"EngineError",
|
|
100
|
+
"SessionClosed",
|
|
101
|
+
"Transport",
|
|
102
|
+
"find_binary",
|
|
103
|
+
"__version__",
|
|
104
|
+
]
|
manul/__main__.py
ADDED
manul/_bin/manul.exe
ADDED
|
Binary file
|
manul/_binary.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Locating the `manul` engine binary.
|
|
2
|
+
|
|
3
|
+
A wheel normally ships the binary inside the package, but a developer working on
|
|
4
|
+
the engine wants their own build to win without reinstalling anything. Hence the
|
|
5
|
+
order below: an explicit override first, the developer's PATH before the bundled
|
|
6
|
+
copy is not offered — an installed wheel should be self-contained and
|
|
7
|
+
predictable, so the bundled binary is preferred over whatever PATH happens to
|
|
8
|
+
hold, and MANUL_BINARY exists for the developer who wants to override that.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import shutil
|
|
15
|
+
import stat
|
|
16
|
+
import sys
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from .errors import EngineNotFound
|
|
20
|
+
|
|
21
|
+
__all__ = ["find_binary", "BINARY_NAME"]
|
|
22
|
+
|
|
23
|
+
BINARY_NAME = "manul.exe" if sys.platform == "win32" else "manul"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _bundled_path() -> Path:
|
|
27
|
+
return Path(__file__).resolve().parent / "_bin" / BINARY_NAME
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _ensure_executable(path: Path) -> None:
|
|
31
|
+
"""Restore the executable bit on the bundled copy if something ate it.
|
|
32
|
+
|
|
33
|
+
The wheel stores the mode and pip restores it, so this is normally a no-op.
|
|
34
|
+
It is not always: a wheel repacked by a mirror, an install onto a filesystem
|
|
35
|
+
with no permission model, or a copy made by hand can all arrive without it.
|
|
36
|
+
A read-only install directory is not an error here — the exec attempt will
|
|
37
|
+
report the real problem in a moment.
|
|
38
|
+
"""
|
|
39
|
+
if os.name == "nt":
|
|
40
|
+
return
|
|
41
|
+
if os.access(path, os.X_OK):
|
|
42
|
+
return
|
|
43
|
+
try:
|
|
44
|
+
mode = path.stat().st_mode
|
|
45
|
+
path.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
|
46
|
+
except OSError:
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def find_binary(explicit: str | os.PathLike[str] | None = None) -> str:
|
|
51
|
+
"""Return the path to the engine binary.
|
|
52
|
+
|
|
53
|
+
Resolution order:
|
|
54
|
+
|
|
55
|
+
1. `explicit`, when the caller passed one.
|
|
56
|
+
2. ``$MANUL_BINARY``.
|
|
57
|
+
3. The copy bundled in this package (what a wheel installs).
|
|
58
|
+
4. ``manul`` on ``PATH``.
|
|
59
|
+
|
|
60
|
+
Raises `EngineNotFound` listing everything that was tried.
|
|
61
|
+
"""
|
|
62
|
+
searched: list[str] = []
|
|
63
|
+
|
|
64
|
+
if explicit:
|
|
65
|
+
p = Path(explicit)
|
|
66
|
+
if p.is_file():
|
|
67
|
+
return str(p)
|
|
68
|
+
searched.append(f"{p} (explicit path)")
|
|
69
|
+
|
|
70
|
+
env = os.environ.get("MANUL_BINARY")
|
|
71
|
+
if env:
|
|
72
|
+
p = Path(env)
|
|
73
|
+
if p.is_file():
|
|
74
|
+
return str(p)
|
|
75
|
+
searched.append(f"{p} (MANUL_BINARY)")
|
|
76
|
+
|
|
77
|
+
bundled = _bundled_path()
|
|
78
|
+
if bundled.is_file():
|
|
79
|
+
_ensure_executable(bundled)
|
|
80
|
+
return str(bundled)
|
|
81
|
+
searched.append(f"{bundled} (bundled with this package)")
|
|
82
|
+
|
|
83
|
+
on_path = shutil.which("manul")
|
|
84
|
+
if on_path:
|
|
85
|
+
return on_path
|
|
86
|
+
searched.append("manul on PATH")
|
|
87
|
+
|
|
88
|
+
raise EngineNotFound(searched)
|
manul/_cli.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""The `manul` console script.
|
|
2
|
+
|
|
3
|
+
A wheel that carries the engine but leaves it buried in `site-packages` is only
|
|
4
|
+
half an install: `manul run checkout.hunt` is how most people meet this project.
|
|
5
|
+
So the entry point is a shim that hands the whole command line to the bundled
|
|
6
|
+
binary and gets out of the way — every subcommand, every flag, no wrapper
|
|
7
|
+
parsing anything it does not have to.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from typing import Sequence
|
|
16
|
+
|
|
17
|
+
from ._binary import find_binary
|
|
18
|
+
from .errors import EngineNotFound
|
|
19
|
+
|
|
20
|
+
__all__ = ["main"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
24
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
binary = find_binary()
|
|
28
|
+
except EngineNotFound as exc:
|
|
29
|
+
print(f"manul: {exc}", file=sys.stderr)
|
|
30
|
+
return 127
|
|
31
|
+
|
|
32
|
+
if os.name == "nt":
|
|
33
|
+
# `execv` on Windows starts a new process and lets this one exit, so the
|
|
34
|
+
# shell returns to the prompt while the engine is still running. Wait for
|
|
35
|
+
# it and pass its exit code on instead.
|
|
36
|
+
try:
|
|
37
|
+
return subprocess.call([binary, *args])
|
|
38
|
+
except KeyboardInterrupt:
|
|
39
|
+
return 130
|
|
40
|
+
except OSError as exc:
|
|
41
|
+
print(f"manul: cannot run {binary}: {exc}", file=sys.stderr)
|
|
42
|
+
return 126
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
os.execv(binary, [binary, *args])
|
|
46
|
+
except OSError as exc:
|
|
47
|
+
# Almost always a lost executable bit — a wheel built on a filesystem
|
|
48
|
+
# that has none, or an installer that dropped the mode.
|
|
49
|
+
print(
|
|
50
|
+
f"manul: cannot execute {binary}: {exc}\n"
|
|
51
|
+
f"If this is a permissions problem: chmod +x {binary}",
|
|
52
|
+
file=sys.stderr,
|
|
53
|
+
)
|
|
54
|
+
return 126
|
|
55
|
+
|
|
56
|
+
return 0 # unreachable: execv replaced this process
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
if __name__ == "__main__":
|
|
60
|
+
sys.exit(main())
|
manul/_hookhost.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""The child half of `manul run --hooks`.
|
|
2
|
+
|
|
3
|
+
Everything else in this package spawns the engine and drives it. This module is
|
|
4
|
+
the one place where that is inverted: the engine spawns *this* process, and this
|
|
5
|
+
process only answers.
|
|
6
|
+
|
|
7
|
+
Nothing here decides anything. Which script to run, which interpreter to run it
|
|
8
|
+
with, when hooks fire and in what order are all the engine's business — this is
|
|
9
|
+
a read-a-line, call-a-function, write-a-line loop over the same NDJSON reverse
|
|
10
|
+
calls a `Session` already handles, and it reuses that same dispatcher.
|
|
11
|
+
|
|
12
|
+
A hook script is therefore just::
|
|
13
|
+
|
|
14
|
+
import manul
|
|
15
|
+
|
|
16
|
+
@manul.before_all
|
|
17
|
+
def sign_in(ctx):
|
|
18
|
+
ctx.set("token", get_token())
|
|
19
|
+
|
|
20
|
+
manul.serve_hooks()
|
|
21
|
+
|
|
22
|
+
and is started with ``manul run hunts/ --hooks manul_hooks.py``.
|
|
23
|
+
|
|
24
|
+
**stdout belongs to the protocol.** A `print()` in a hook script would land in
|
|
25
|
+
the middle of a JSON line and break the engine's parser, so this module points
|
|
26
|
+
`sys.stdout` at stderr for the duration and hands the real stream to the writer.
|
|
27
|
+
That is the same rule the engine imposes on itself in serve mode, applied in the
|
|
28
|
+
one direction a user is likely to trip over.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import json
|
|
34
|
+
import sys
|
|
35
|
+
from typing import Any, TextIO
|
|
36
|
+
|
|
37
|
+
from . import controls
|
|
38
|
+
|
|
39
|
+
__all__ = ["serve_hooks"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class _HookHost:
|
|
43
|
+
"""One conversation with the engine that started this process."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, stdin: TextIO, stdout: TextIO) -> None:
|
|
46
|
+
self._in = stdin
|
|
47
|
+
self._out = stdout
|
|
48
|
+
self._id = 0
|
|
49
|
+
|
|
50
|
+
# ── wire ────────────────────────────────────────────────────────────────
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def _encode(payload: dict[str, Any]) -> str:
|
|
54
|
+
return json.dumps(payload, separators=(",", ":"))
|
|
55
|
+
|
|
56
|
+
def _send(self, payload: dict[str, Any]) -> None:
|
|
57
|
+
self._write(self._encode(payload))
|
|
58
|
+
|
|
59
|
+
def _write(self, line: str) -> None:
|
|
60
|
+
self._out.write(line + "\n")
|
|
61
|
+
self._out.flush()
|
|
62
|
+
|
|
63
|
+
def _readline(self) -> dict[str, Any] | None:
|
|
64
|
+
while True:
|
|
65
|
+
line = self._in.readline()
|
|
66
|
+
if line == "":
|
|
67
|
+
return None # engine closed our input: time to exit
|
|
68
|
+
line = line.strip().lstrip("")
|
|
69
|
+
if not line:
|
|
70
|
+
continue
|
|
71
|
+
return json.loads(line)
|
|
72
|
+
|
|
73
|
+
def _call(self, cmd: str, args: dict[str, Any] | None = None) -> Any:
|
|
74
|
+
"""Send a command to the engine and wait for its reply."""
|
|
75
|
+
self._id += 1
|
|
76
|
+
req_id = self._id
|
|
77
|
+
payload: dict[str, Any] = {"id": req_id, "cmd": cmd}
|
|
78
|
+
if args is not None:
|
|
79
|
+
payload["args"] = args
|
|
80
|
+
self._send(payload)
|
|
81
|
+
|
|
82
|
+
msg = self._readline()
|
|
83
|
+
if msg is None:
|
|
84
|
+
raise ConnectionError(f"engine closed the stream while {cmd!r} was pending")
|
|
85
|
+
if not msg.get("ok"):
|
|
86
|
+
err = msg.get("error") or {}
|
|
87
|
+
raise RuntimeError(f"{cmd}: {err.get('message', 'rejected by the engine')}")
|
|
88
|
+
return msg.get("result")
|
|
89
|
+
|
|
90
|
+
# ── page primitives ─────────────────────────────────────────────────────
|
|
91
|
+
#
|
|
92
|
+
# Named to match Session, because the handler contexts reach for these on
|
|
93
|
+
# whatever object owns the pipe and must not care which one it is.
|
|
94
|
+
|
|
95
|
+
def _page_eval(self, js: str) -> Any:
|
|
96
|
+
return self._call("page.eval", {"js": js})
|
|
97
|
+
|
|
98
|
+
def _page_url(self) -> str:
|
|
99
|
+
return self._call("page.url") or ""
|
|
100
|
+
|
|
101
|
+
# ── loop ────────────────────────────────────────────────────────────────
|
|
102
|
+
|
|
103
|
+
def run(self) -> int:
|
|
104
|
+
payload = controls._registration_payload()
|
|
105
|
+
if any(payload.values()):
|
|
106
|
+
self._call("register", payload)
|
|
107
|
+
self._call("ready")
|
|
108
|
+
|
|
109
|
+
while True:
|
|
110
|
+
msg = self._readline()
|
|
111
|
+
if msg is None:
|
|
112
|
+
return 0
|
|
113
|
+
if "invoke" not in msg:
|
|
114
|
+
# The engine only ever writes invocations here; anything else
|
|
115
|
+
# means the two sides disagree about the protocol, and guessing
|
|
116
|
+
# would corrupt the stream rather than fail it.
|
|
117
|
+
raise RuntimeError(f"expected an invocation, got {msg!r}")
|
|
118
|
+
|
|
119
|
+
invoke_id = msg["invoke"]
|
|
120
|
+
try:
|
|
121
|
+
result = controls.dispatch_invoke(msg, self)
|
|
122
|
+
# Encoded inside the try: a result JSON cannot carry is that
|
|
123
|
+
# handler's failure, not a reason for the whole host to die and
|
|
124
|
+
# take every later hook with it.
|
|
125
|
+
line = self._encode({"invoke": invoke_id, "ok": True, "result": result})
|
|
126
|
+
except Exception as exc: # a failing handler is an answer, not a crash
|
|
127
|
+
line = self._encode({
|
|
128
|
+
"invoke": invoke_id,
|
|
129
|
+
"ok": False,
|
|
130
|
+
"error": {"code": "handler_failed", "message": f"{type(exc).__name__}: {exc}"},
|
|
131
|
+
})
|
|
132
|
+
self._write(line)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def serve_hooks() -> int:
|
|
136
|
+
"""Answer the engine's callbacks until it closes this process's input.
|
|
137
|
+
|
|
138
|
+
Call it at the end of a hook script. It blocks, and returns only when the
|
|
139
|
+
run is over.
|
|
140
|
+
"""
|
|
141
|
+
real_stdout = sys.stdout
|
|
142
|
+
# The engine writes UTF-8 whatever this machine's locale says. A pipe on
|
|
143
|
+
# Windows defaults to the ANSI code page, which turns every non-ASCII label,
|
|
144
|
+
# value and variable into mojibake before a handler ever sees it.
|
|
145
|
+
for stream in (sys.stdin, real_stdout):
|
|
146
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
147
|
+
if reconfigure is not None:
|
|
148
|
+
reconfigure(encoding="utf-8")
|
|
149
|
+
sys.stdout = sys.stderr # see the module docstring
|
|
150
|
+
try:
|
|
151
|
+
return _HookHost(sys.stdin, real_stdout).run()
|
|
152
|
+
finally:
|
|
153
|
+
sys.stdout = real_stdout
|
manul/_transport.py
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"""NDJSON-over-stdio transport for `manul serve`.
|
|
2
|
+
|
|
3
|
+
This module owns the child process and the wire format, and nothing else. It
|
|
4
|
+
does not know what a page or a step is — that lives in `session.py`. Keeping the
|
|
5
|
+
split means the protocol can gain commands without this file changing.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import subprocess
|
|
13
|
+
import threading
|
|
14
|
+
from typing import Any, IO, Sequence
|
|
15
|
+
|
|
16
|
+
from ._binary import find_binary
|
|
17
|
+
from .errors import EngineError, ProtocolError, SessionClosed
|
|
18
|
+
|
|
19
|
+
__all__ = ["Transport", "SUPPORTED_PROTOCOL_MAJOR"]
|
|
20
|
+
|
|
21
|
+
# This binding is written against protocol 1.x. Minor bumps only add things, so
|
|
22
|
+
# they are safe; a major bump changes existing shapes and must be refused.
|
|
23
|
+
SUPPORTED_PROTOCOL_MAJOR = 1
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Transport:
|
|
27
|
+
"""A live `manul serve --stdio` process.
|
|
28
|
+
|
|
29
|
+
Requests are synchronous: each `call` writes one line and reads until the
|
|
30
|
+
reply with a matching id arrives, passing over any events in between.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
binary: str | os.PathLike[str] | Sequence[str] | None = None,
|
|
36
|
+
*,
|
|
37
|
+
args: list[str] | None = None,
|
|
38
|
+
stderr: IO[Any] | None = None,
|
|
39
|
+
cwd: str | os.PathLike[str] | None = None,
|
|
40
|
+
env: dict[str, str] | None = None,
|
|
41
|
+
) -> None:
|
|
42
|
+
# A sequence is taken verbatim as the command prefix, so the engine can
|
|
43
|
+
# be reached through a wrapper — `wsl`, `docker exec`, a shim script —
|
|
44
|
+
# without this package needing to know about any of them.
|
|
45
|
+
if isinstance(binary, (list, tuple)):
|
|
46
|
+
prefix = [str(part) for part in binary]
|
|
47
|
+
if not prefix:
|
|
48
|
+
raise ValueError("binary sequence is empty")
|
|
49
|
+
else:
|
|
50
|
+
prefix = [find_binary(binary)]
|
|
51
|
+
self._path = prefix[0]
|
|
52
|
+
|
|
53
|
+
self._next_id = 0
|
|
54
|
+
self._closed = False
|
|
55
|
+
self._lock = threading.Lock()
|
|
56
|
+
|
|
57
|
+
argv = [*prefix, "serve", "--stdio", *(args or [])]
|
|
58
|
+
self._proc = subprocess.Popen(
|
|
59
|
+
argv,
|
|
60
|
+
stdin=subprocess.PIPE,
|
|
61
|
+
stdout=subprocess.PIPE,
|
|
62
|
+
# Engine logs go to stderr and are never parsed. Left inheriting the
|
|
63
|
+
# parent's stderr by default so warnings stay visible.
|
|
64
|
+
stderr=stderr,
|
|
65
|
+
cwd=cwd,
|
|
66
|
+
env=env,
|
|
67
|
+
text=True,
|
|
68
|
+
encoding="utf-8",
|
|
69
|
+
bufsize=1,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
self.protocol: str = ""
|
|
73
|
+
self.engine_version: str = ""
|
|
74
|
+
|
|
75
|
+
# on_invoke handles reverse calls — the engine asking this process to
|
|
76
|
+
# run a custom control or a CALL handler. Set by Session; without it an
|
|
77
|
+
# invoke is answered with an error rather than left to hang.
|
|
78
|
+
self.on_invoke: Any = None
|
|
79
|
+
|
|
80
|
+
self._read_ready()
|
|
81
|
+
|
|
82
|
+
# ── lifecycle ────────────────────────────────────────────────────────────
|
|
83
|
+
|
|
84
|
+
def _read_ready(self) -> None:
|
|
85
|
+
"""Consume the ready event the engine always writes first.
|
|
86
|
+
|
|
87
|
+
A process that dies before emitting it is reported as a startup failure
|
|
88
|
+
rather than left to hang on the first real request.
|
|
89
|
+
"""
|
|
90
|
+
line = self._readline()
|
|
91
|
+
if line is None:
|
|
92
|
+
raise ProtocolError(
|
|
93
|
+
f"engine at {self._path} exited before sending the ready event"
|
|
94
|
+
f" (exit code {self._proc.poll()})"
|
|
95
|
+
)
|
|
96
|
+
try:
|
|
97
|
+
msg = json.loads(line)
|
|
98
|
+
except json.JSONDecodeError as exc:
|
|
99
|
+
raise ProtocolError(f"first line was not JSON: {line!r}") from exc
|
|
100
|
+
|
|
101
|
+
if msg.get("event") != "ready":
|
|
102
|
+
raise ProtocolError(f"expected a ready event, got {msg!r}")
|
|
103
|
+
|
|
104
|
+
self.protocol = str(msg.get("protocol", ""))
|
|
105
|
+
self.engine_version = str(msg.get("engine", ""))
|
|
106
|
+
|
|
107
|
+
major = self.protocol.split(".", 1)[0]
|
|
108
|
+
if major != str(SUPPORTED_PROTOCOL_MAJOR):
|
|
109
|
+
raise ProtocolError(
|
|
110
|
+
f"engine speaks protocol {self.protocol}, this binding supports "
|
|
111
|
+
f"{SUPPORTED_PROTOCOL_MAJOR}.x — upgrade the manul package"
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def closed(self) -> bool:
|
|
116
|
+
return self._closed
|
|
117
|
+
|
|
118
|
+
def close(self, timeout: float = 5.0) -> None:
|
|
119
|
+
"""Shut the engine down, politely first.
|
|
120
|
+
|
|
121
|
+
`close` gives the engine a chance to release its browser; only a process
|
|
122
|
+
that ignores that is killed.
|
|
123
|
+
"""
|
|
124
|
+
if self._closed:
|
|
125
|
+
return
|
|
126
|
+
self._closed = True
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
self._send({"id": self._take_id(), "cmd": "close"})
|
|
130
|
+
self._readline()
|
|
131
|
+
except (OSError, ValueError, ProtocolError):
|
|
132
|
+
pass
|
|
133
|
+
|
|
134
|
+
try:
|
|
135
|
+
if self._proc.stdin:
|
|
136
|
+
self._proc.stdin.close()
|
|
137
|
+
except OSError:
|
|
138
|
+
pass
|
|
139
|
+
|
|
140
|
+
try:
|
|
141
|
+
self._proc.wait(timeout=timeout)
|
|
142
|
+
except subprocess.TimeoutExpired:
|
|
143
|
+
self._proc.kill()
|
|
144
|
+
self._proc.wait()
|
|
145
|
+
|
|
146
|
+
def __enter__(self) -> "Transport":
|
|
147
|
+
return self
|
|
148
|
+
|
|
149
|
+
def __exit__(self, *_exc: object) -> None:
|
|
150
|
+
self.close()
|
|
151
|
+
|
|
152
|
+
# ── wire ─────────────────────────────────────────────────────────────────
|
|
153
|
+
|
|
154
|
+
def call(self, cmd: str, args: dict[str, Any] | None = None) -> Any:
|
|
155
|
+
"""Send one command and return its result.
|
|
156
|
+
|
|
157
|
+
Raises `EngineError` when the engine answers ``ok: false`` — the session
|
|
158
|
+
stays usable, so callers may catch it and carry on.
|
|
159
|
+
"""
|
|
160
|
+
if self._closed:
|
|
161
|
+
raise SessionClosed("session is closed")
|
|
162
|
+
|
|
163
|
+
with self._lock:
|
|
164
|
+
req_id = self._take_id()
|
|
165
|
+
req: dict[str, Any] = {"id": req_id, "cmd": cmd}
|
|
166
|
+
if args:
|
|
167
|
+
# Drop unset optionals so the engine sees its own defaults
|
|
168
|
+
# rather than a wall of nulls.
|
|
169
|
+
req["args"] = {k: v for k, v in args.items() if v is not None}
|
|
170
|
+
self._send(req)
|
|
171
|
+
return self._await_reply(req_id)
|
|
172
|
+
|
|
173
|
+
def _await_reply(self, req_id: int) -> Any:
|
|
174
|
+
while True:
|
|
175
|
+
line = self._readline()
|
|
176
|
+
if line is None:
|
|
177
|
+
raise ProtocolError(
|
|
178
|
+
f"engine exited while waiting for reply {req_id} "
|
|
179
|
+
f"(exit code {self._proc.poll()})"
|
|
180
|
+
)
|
|
181
|
+
try:
|
|
182
|
+
msg = json.loads(line)
|
|
183
|
+
except json.JSONDecodeError as exc:
|
|
184
|
+
raise ProtocolError(f"unreadable line: {line!r}") from exc
|
|
185
|
+
|
|
186
|
+
# A reverse call: run the handler here and answer it, then carry on
|
|
187
|
+
# waiting. The engine is paused inside our request until we do.
|
|
188
|
+
if "invoke" in msg:
|
|
189
|
+
self._serve_invoke(msg)
|
|
190
|
+
continue
|
|
191
|
+
|
|
192
|
+
# Events carry no id and may arrive at any time.
|
|
193
|
+
if "event" in msg and "id" not in msg:
|
|
194
|
+
continue
|
|
195
|
+
if msg.get("id") != req_id:
|
|
196
|
+
continue
|
|
197
|
+
|
|
198
|
+
if msg.get("ok"):
|
|
199
|
+
return msg.get("result")
|
|
200
|
+
err = msg.get("error") or {}
|
|
201
|
+
raise EngineError(
|
|
202
|
+
str(err.get("code", "unknown")),
|
|
203
|
+
str(err.get("message", "engine reported a failure")),
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
def _serve_invoke(self, msg: dict[str, Any]) -> None:
|
|
207
|
+
"""Run one reverse call and write its result back.
|
|
208
|
+
|
|
209
|
+
A handler that raises is reported to the engine, which fails the step —
|
|
210
|
+
the session itself stays healthy, because a broken handler is a bug in
|
|
211
|
+
one step, not a reason to tear down the browser.
|
|
212
|
+
"""
|
|
213
|
+
invoke_id = msg.get("invoke")
|
|
214
|
+
try:
|
|
215
|
+
if self.on_invoke is None:
|
|
216
|
+
raise LookupError(
|
|
217
|
+
f"engine asked for {msg.get('kind')!r} but no handler is registered"
|
|
218
|
+
)
|
|
219
|
+
result = self.on_invoke(msg)
|
|
220
|
+
# Encoded here, inside the try. A handler may return something JSON
|
|
221
|
+
# cannot carry — a datetime, a Decimal, a set — and that has to fail
|
|
222
|
+
# its own step like any other handler error. Raised from the write
|
|
223
|
+
# instead, it escaped with the engine still waiting on this reply,
|
|
224
|
+
# and every later call on the session hung behind it.
|
|
225
|
+
reply = self._encode({"invoke": invoke_id, "ok": True, "result": result})
|
|
226
|
+
except BaseException as exc: # noqa: BLE001 - reported, never swallowed
|
|
227
|
+
self._send({
|
|
228
|
+
"invoke": invoke_id,
|
|
229
|
+
"ok": False,
|
|
230
|
+
"error": {
|
|
231
|
+
"code": "handler_failed",
|
|
232
|
+
"message": f"{type(exc).__name__}: {exc}",
|
|
233
|
+
},
|
|
234
|
+
})
|
|
235
|
+
else:
|
|
236
|
+
self._write(reply)
|
|
237
|
+
|
|
238
|
+
def nested_call(self, cmd: str, args: dict[str, Any] | None = None) -> Any:
|
|
239
|
+
"""Issue a request from inside a reverse call.
|
|
240
|
+
|
|
241
|
+
Only the engine's `page.*` primitives are available here — everything
|
|
242
|
+
else would re-enter the step that is currently running. It bypasses the
|
|
243
|
+
lock deliberately: the caller is already inside a `call` that holds it.
|
|
244
|
+
"""
|
|
245
|
+
req_id = self._take_id()
|
|
246
|
+
req: dict[str, Any] = {"id": req_id, "cmd": cmd}
|
|
247
|
+
if args:
|
|
248
|
+
req["args"] = {k: v for k, v in args.items() if v is not None}
|
|
249
|
+
self._send(req)
|
|
250
|
+
return self._await_reply(req_id)
|
|
251
|
+
|
|
252
|
+
def _take_id(self) -> int:
|
|
253
|
+
self._next_id += 1
|
|
254
|
+
return self._next_id
|
|
255
|
+
|
|
256
|
+
@staticmethod
|
|
257
|
+
def _encode(payload: dict[str, Any]) -> str:
|
|
258
|
+
return json.dumps(payload, ensure_ascii=False)
|
|
259
|
+
|
|
260
|
+
def _send(self, payload: dict[str, Any]) -> None:
|
|
261
|
+
self._write(self._encode(payload))
|
|
262
|
+
|
|
263
|
+
def _write(self, line: str) -> None:
|
|
264
|
+
stdin = self._proc.stdin
|
|
265
|
+
if stdin is None:
|
|
266
|
+
raise ProtocolError("engine stdin is not available")
|
|
267
|
+
stdin.write(line + "\n")
|
|
268
|
+
stdin.flush()
|
|
269
|
+
|
|
270
|
+
def _readline(self) -> str | None:
|
|
271
|
+
stdout = self._proc.stdout
|
|
272
|
+
if stdout is None:
|
|
273
|
+
return None
|
|
274
|
+
line = stdout.readline()
|
|
275
|
+
if line == "":
|
|
276
|
+
return None
|
|
277
|
+
return line.strip()
|