aether-browser 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.
@@ -0,0 +1,38 @@
1
+ """Client for the Agent Browser v1 API.
2
+
3
+ The server exposes one closed JSON API. Every request and response carries
4
+ ``api_version: "v1"`` and unknown fields are rejected, so this client sends exactly
5
+ the documented fields and omits anything left unset.
6
+
7
+ This is the Python sibling of the ``aether-browser`` npm package: same name, same
8
+ surface, same closed contract.
9
+
10
+ See https://github.com/AetherAI3/agent-browser/blob/main/docs/API.md
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from ._client import (
16
+ ALLOWED_KEYS,
17
+ API_VERSION,
18
+ DEFAULT_BASE_URL,
19
+ AgentBrowser,
20
+ AgentBrowserError,
21
+ Response,
22
+ Session,
23
+ session,
24
+ )
25
+
26
+ __all__ = [
27
+ "ALLOWED_KEYS",
28
+ "API_VERSION",
29
+ "DEFAULT_BASE_URL",
30
+ "AgentBrowser",
31
+ "AgentBrowserError",
32
+ "Response",
33
+ "Session",
34
+ "__version__",
35
+ "session",
36
+ ]
37
+
38
+ __version__ = "0.1.0"
@@ -0,0 +1,390 @@
1
+ """The Agent Browser v1 client.
2
+
3
+ Zero runtime dependencies by design: the transport is :mod:`urllib.request` from the
4
+ standard library, and it is injectable so tests never touch a socket.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import urllib.error
12
+ import urllib.request
13
+ from collections.abc import Callable, Iterator, Mapping
14
+ from contextlib import contextmanager
15
+ from typing import Any, NamedTuple
16
+
17
+ API_VERSION = "v1"
18
+
19
+ DEFAULT_BASE_URL = "http://127.0.0.1:8092"
20
+
21
+ #: Keys the server accepts for ``press``. Anything else is refused server-side.
22
+ ALLOWED_KEYS: tuple[str, ...] = (
23
+ "Enter",
24
+ "Escape",
25
+ "Tab",
26
+ "Backspace",
27
+ "Delete",
28
+ "Space",
29
+ "ArrowUp",
30
+ "ArrowDown",
31
+ "ArrowLeft",
32
+ "ArrowRight",
33
+ "Home",
34
+ "End",
35
+ "PageUp",
36
+ "PageDown",
37
+ "Control+A",
38
+ "Control+Z",
39
+ "Control+Shift+Z",
40
+ "Meta+A",
41
+ "Meta+Z",
42
+ "Meta+Shift+Z",
43
+ )
44
+
45
+ DEFAULT_TIMEOUT = 30.0
46
+
47
+
48
+ class Response(NamedTuple):
49
+ """What a transport returns: the raw status, headers, and body text."""
50
+
51
+ status: int
52
+ headers: Mapping[str, str]
53
+ text: str
54
+
55
+
56
+ #: ``(method, url, headers, body, timeout) -> Response``. ``timeout`` is ``None`` when
57
+ #: the caller disabled it, and ``body`` is ``None`` for a request without one.
58
+ Transport = Callable[[str, str, Mapping[str, str], "bytes | None", "float | None"], Response]
59
+
60
+
61
+ class AgentBrowserError(Exception):
62
+ """An error returned by the Agent Browser API, or a transport failure reaching it.
63
+
64
+ ``code`` is the server's stable error code when the response carried the documented
65
+ error envelope, and ``None`` for transport-level failures.
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ message: str,
71
+ *,
72
+ code: str | None = None,
73
+ http_status: int | None = None,
74
+ retry_after_seconds: float | None = None,
75
+ ) -> None:
76
+ super().__init__(message)
77
+ self.code = code
78
+ self.http_status = http_status
79
+ self.retry_after_seconds = retry_after_seconds
80
+
81
+ @property
82
+ def is_capacity_reached(self) -> bool:
83
+ """True when the server refused because a session is already active."""
84
+ return self.code == "SESSION_CAPACITY_REACHED"
85
+
86
+ @property
87
+ def is_destination_blocked(self) -> bool:
88
+ """True when the server refused the destination rather than failing to reach it."""
89
+ return self.code in {"DESTINATION_BLOCKED", "INVALID_URL"}
90
+
91
+
92
+ def _compact(values: Mapping[str, Any]) -> dict[str, Any]:
93
+ """Strip unset values so the closed server models never see unknown or null keys."""
94
+ return {key: value for key, value in values.items() if value is not None}
95
+
96
+
97
+ def _normalize_base_url(value: str) -> str:
98
+ """Trim trailing slashes by scanning.
99
+
100
+ A regular expression such as ``/\\/+$/`` backtracks polynomially on a long run of
101
+ slashes. The base URL is normally the caller's own config, but a linear scan costs
102
+ nothing and removes the failure mode outright.
103
+ """
104
+ text = str(value)
105
+ end = len(text)
106
+ while end > 0 and text[end - 1] == "/":
107
+ end -= 1
108
+ return text[:end]
109
+
110
+
111
+ def _urllib_transport(
112
+ method: str,
113
+ url: str,
114
+ headers: Mapping[str, str],
115
+ body: bytes | None,
116
+ timeout: float | None,
117
+ ) -> Response:
118
+ if not url.startswith(("http://", "https://")):
119
+ raise AgentBrowserError(f"Refusing a non-HTTP(S) Agent Browser URL: {url}")
120
+ # The scheme is checked above, which is what S310 asks for.
121
+ request = urllib.request.Request(url, data=body, headers=dict(headers), method=method) # noqa: S310
122
+ try:
123
+ with urllib.request.urlopen(request, timeout=timeout) as reply: # noqa: S310
124
+ return Response(reply.status, dict(reply.headers), reply.read().decode("utf-8"))
125
+ except urllib.error.HTTPError as error:
126
+ # An HTTP error is a real, documented response: read it rather than raising, so
127
+ # the caller gets the server's error envelope instead of a transport failure.
128
+ return Response(error.code, dict(error.headers or {}), error.read().decode("utf-8"))
129
+
130
+
131
+ class Session:
132
+ """A live session. Obtained from :meth:`AgentBrowser.create_session`.
133
+
134
+ Every method is a thin call onto a documented route. The session does not cache page
135
+ state: ``navigate`` and ``snapshot`` each return the server's own bounded view.
136
+ """
137
+
138
+ def __init__(self, browser: AgentBrowser, created: Mapping[str, Any]) -> None:
139
+ self.browser = browser
140
+ self.id: str = created["session_id"]
141
+ self.view_url: str | None = created.get("view_url")
142
+ self.created_at: str | None = created.get("created_at")
143
+ self.expires_at: str | None = created.get("expires_at")
144
+ self.max_vision_steps: int | None = created.get("max_vision_steps")
145
+ self.ended = False
146
+
147
+ def navigate(self, url: str, *, timeout: float | None = None) -> dict[str, Any]:
148
+ """Navigate to an HTTP(S) URL.
149
+
150
+ The server evaluates its egress policy separately from schema validation.
151
+ """
152
+ return self.browser._post(
153
+ "/browser/navigate", {"session_id": self.id, "url": url}, "controller", timeout
154
+ )
155
+
156
+ def snapshot(self, *, timeout: float | None = None) -> dict[str, Any]:
157
+ """Capture bounded page state plus a base64 PNG. Consumes exactly one vision step."""
158
+ return self.browser._post("/browser/snapshot", {"session_id": self.id}, "observer", timeout)
159
+
160
+ def click(
161
+ self,
162
+ *,
163
+ selector: str | None = None,
164
+ x: int | None = None,
165
+ y: int | None = None,
166
+ timeout: float | None = None,
167
+ ) -> dict[str, Any]:
168
+ """Click a selector or an x/y point. Exactly one of the two is allowed by the server."""
169
+ return self._interact(
170
+ {"action": "click", "target": _compact({"selector": selector, "x": x, "y": y})},
171
+ timeout,
172
+ )
173
+
174
+ def type(
175
+ self,
176
+ text: str,
177
+ *,
178
+ selector: str | None = None,
179
+ x: int | None = None,
180
+ y: int | None = None,
181
+ timeout: float | None = None,
182
+ ) -> dict[str, Any]:
183
+ """Type text into a selector or an x/y point.
184
+
185
+ Text is preserved byte for byte, including leading and trailing whitespace.
186
+ """
187
+ return self._interact(
188
+ {
189
+ "action": "type",
190
+ "target": _compact({"selector": selector, "x": x, "y": y}),
191
+ "text": text,
192
+ },
193
+ timeout,
194
+ )
195
+
196
+ def press(self, key: str, *, timeout: float | None = None) -> dict[str, Any]:
197
+ """Press one of the allowed keys or combinations.
198
+
199
+ Clipboard shortcuts are not allowlisted; :data:`ALLOWED_KEYS` is the full set.
200
+ """
201
+ return self._interact({"action": "press", "key": key}, timeout)
202
+
203
+ def scroll(
204
+ self,
205
+ *,
206
+ delta_x: int | None = None,
207
+ delta_y: int | None = None,
208
+ selector: str | None = None,
209
+ x: int | None = None,
210
+ y: int | None = None,
211
+ timeout: float | None = None,
212
+ ) -> dict[str, Any]:
213
+ """Scroll by a bounded, nonzero delta."""
214
+ body: dict[str, Any] = _compact(
215
+ {"action": "scroll", "delta_x": delta_x, "delta_y": delta_y}
216
+ )
217
+ target = _compact({"selector": selector, "x": x, "y": y})
218
+ if target:
219
+ body["target"] = target
220
+ return self._interact(body, timeout)
221
+
222
+ def end(self, *, timeout: float | None = None) -> dict[str, Any]:
223
+ """End the session.
224
+
225
+ Idempotent: a repeated call reports ``already_ended`` rather than resurrecting
226
+ state, so calling this twice is safe.
227
+ """
228
+ result = self.browser._post(
229
+ "/browser/session/end", {"session_id": self.id}, "controller", timeout
230
+ )
231
+ self.ended = True
232
+ return result
233
+
234
+ def _interact(self, body: Mapping[str, Any], timeout: float | None) -> dict[str, Any]:
235
+ return self.browser._post(
236
+ "/browser/interact", {"session_id": self.id, **body}, "controller", timeout
237
+ )
238
+
239
+
240
+ class AgentBrowser:
241
+ """A client bound to one Agent Browser server.
242
+
243
+ Observer and controller tokens are kept separate so the server's role split is visible
244
+ in your own code: reads may be given only the observer token, while anything that
245
+ creates, navigates, interacts, or ends requires the controller token.
246
+ """
247
+
248
+ def __init__(
249
+ self,
250
+ *,
251
+ base_url: str | None = None,
252
+ controller_token: str | None = None,
253
+ observer_token: str | None = None,
254
+ timeout: float | None = DEFAULT_TIMEOUT,
255
+ env: Mapping[str, str] | None = None,
256
+ transport: Transport | None = None,
257
+ ) -> None:
258
+ environment = os.environ if env is None else env
259
+ self.base_url = _normalize_base_url(
260
+ base_url
261
+ if base_url is not None
262
+ else environment.get("AGENT_BROWSER_URL", DEFAULT_BASE_URL)
263
+ )
264
+ self.controller_token = (
265
+ controller_token
266
+ if controller_token is not None
267
+ else environment.get("AGENT_BROWSER_CONTROLLER_TOKEN")
268
+ )
269
+ self.observer_token = (
270
+ observer_token
271
+ if observer_token is not None
272
+ else environment.get("AGENT_BROWSER_OBSERVER_TOKEN")
273
+ )
274
+ self.timeout = timeout
275
+ self._transport: Transport = transport if transport is not None else _urllib_transport
276
+
277
+ def health(self, *, timeout: float | None = None) -> dict[str, Any]:
278
+ """Liveness and readiness. Accepts the observer token."""
279
+ return self._request("GET", "/browser/health", None, "observer", timeout)
280
+
281
+ def create_session(
282
+ self, *, max_vision_steps: int | None = None, timeout: float | None = None
283
+ ) -> Session:
284
+ """Create the one owned session.
285
+
286
+ A second concurrent create is refused with ``SESSION_CAPACITY_REACHED`` rather
287
+ than queued.
288
+ """
289
+ created = self._post(
290
+ "/browser/session/create",
291
+ _compact({"max_vision_steps": max_vision_steps}),
292
+ "controller",
293
+ timeout,
294
+ )
295
+ return Session(self, created)
296
+
297
+ def _post(
298
+ self, path: str, body: Mapping[str, Any], role: str, timeout: float | None
299
+ ) -> dict[str, Any]:
300
+ return self._request("POST", path, body, role, timeout)
301
+
302
+ def _token_for(self, role: str) -> str | None:
303
+ if role == "observer":
304
+ return self.observer_token or self.controller_token
305
+ return self.controller_token or self.observer_token
306
+
307
+ def _request(
308
+ self,
309
+ method: str,
310
+ path: str,
311
+ body: Mapping[str, Any] | None,
312
+ role: str,
313
+ timeout: float | None,
314
+ ) -> dict[str, Any]:
315
+ headers = {"accept": "application/json"}
316
+ token = self._token_for(role)
317
+ if token:
318
+ headers["authorization"] = f"Bearer {token}"
319
+
320
+ payload: bytes | None = None
321
+ if body is not None:
322
+ headers["content-type"] = "application/json"
323
+ payload = json.dumps({"api_version": API_VERSION, **body}).encode("utf-8")
324
+
325
+ effective_timeout = self.timeout if timeout is None else timeout
326
+ if effective_timeout is not None and effective_timeout <= 0:
327
+ effective_timeout = None
328
+
329
+ url = f"{self.base_url}{path}"
330
+ try:
331
+ response = self._transport(method, url, headers, payload, effective_timeout)
332
+ except AgentBrowserError:
333
+ raise
334
+ except Exception as cause: # every transport failure reads the same to the caller
335
+ raise AgentBrowserError(
336
+ f"Could not reach Agent Browser at {self.base_url}: {cause}"
337
+ ) from cause
338
+
339
+ try:
340
+ parsed = json.loads(response.text) if response.text else None
341
+ except ValueError:
342
+ parsed = None
343
+
344
+ if response.status >= 400:
345
+ detail = parsed.get("error") if isinstance(parsed, dict) else None
346
+ message = None
347
+ if isinstance(detail, Mapping):
348
+ message = detail.get("message")
349
+ raise AgentBrowserError(
350
+ message or f"Agent Browser returned HTTP {response.status}",
351
+ code=detail.get("code") if isinstance(detail, Mapping) else None,
352
+ http_status=response.status,
353
+ retry_after_seconds=_retry_after(response.headers),
354
+ )
355
+
356
+ return parsed if isinstance(parsed, dict) else {}
357
+
358
+
359
+ def _retry_after(headers: Mapping[str, str]) -> float | None:
360
+ raw = None
361
+ for name, value in headers.items():
362
+ if name.lower() == "retry-after":
363
+ raw = value
364
+ break
365
+ if raw is None:
366
+ return None
367
+ try:
368
+ return float(raw)
369
+ except (TypeError, ValueError):
370
+ return None
371
+
372
+
373
+ @contextmanager
374
+ def session(browser: AgentBrowser, *, max_vision_steps: int | None = None) -> Iterator[Session]:
375
+ """Run a block against a fresh session and always attempt to end it.
376
+
377
+ A failure to end never masks the original error, and a session that was never
378
+ created is never ended.
379
+
380
+ >>> with session(AgentBrowser()) as live: # doctest: +SKIP
381
+ ... live.navigate("https://example.com")
382
+ """
383
+ live = browser.create_session(max_vision_steps=max_vision_steps)
384
+ try:
385
+ yield live
386
+ finally:
387
+ try:
388
+ live.end()
389
+ except Exception: # noqa: S110 - the caller's outcome must not be replaced
390
+ pass
aether_browser/cli.py ADDED
@@ -0,0 +1,351 @@
1
+ """The ``aether-browser`` command line.
2
+
3
+ The runtime is a container you build from source: Agent Browser publishes no
4
+ Chrome-containing image, so ``up`` builds one locally the first time and that build takes
5
+ several minutes. This CLI never pretends otherwise.
6
+
7
+ It mirrors the ``aether-browser`` npm CLI command for command, so the two ecosystems give
8
+ the same answers on the same machine.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import platform
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ from . import __version__
22
+ from ._client import DEFAULT_BASE_URL, AgentBrowser, AgentBrowserError
23
+
24
+ REPO = "https://github.com/AetherAI3/agent-browser"
25
+ NOVNC_URL = "http://127.0.0.1:6080/vnc.html"
26
+ # The published source tag for this client. `up` builds this exact tree, so the container
27
+ # and the client always speak the same api_version.
28
+ SOURCE_TAG = "v0.1.0"
29
+
30
+ _COLOR = sys.stdout.isatty() and not os.environ.get("NO_COLOR")
31
+
32
+
33
+ def _paint(code: str, text: str) -> str:
34
+ return f"\033[{code}m{text}\033[0m" if _COLOR else text
35
+
36
+
37
+ def _dim(text: str) -> str:
38
+ return _paint("2", text)
39
+
40
+
41
+ def _bold(text: str) -> str:
42
+ return _paint("1", text)
43
+
44
+
45
+ def _ok(text: str) -> None:
46
+ print(f" {_paint('32', 'ok')} {text}")
47
+
48
+
49
+ def _warn(text: str) -> None:
50
+ print(f" {_paint('33', 'warn')} {text}")
51
+
52
+
53
+ def _bad(text: str) -> None:
54
+ print(f" {_paint('31', 'fail')} {text}")
55
+
56
+
57
+ def _run(command: list[str]) -> subprocess.CompletedProcess[str]:
58
+ """Run a fixed command with no shell.
59
+
60
+ Every argument list here is a literal built in this module, so S603 (untrusted input)
61
+ and S607 (partial path) do not apply: resolving `docker` and `tar` through PATH is the
62
+ behaviour a developer expects from a developer tool.
63
+ """
64
+ return subprocess.run(command, capture_output=True, text=True, check=False) # noqa: S603
65
+
66
+
67
+ def _version_of(command: str) -> str | None:
68
+ if shutil.which(command) is None:
69
+ return None
70
+ probe = _run([command, "--version"])
71
+ if probe.returncode != 0:
72
+ return None
73
+ return (probe.stdout or probe.stderr).strip().splitlines()[0]
74
+
75
+
76
+ def _compose_version() -> str | None:
77
+ if shutil.which("docker") is None:
78
+ return None
79
+ probe = _run(["docker", "compose", "version"])
80
+ return probe.stdout.strip() if probe.returncode == 0 else None
81
+
82
+
83
+ def _find_compose_dir(*, allow_download: bool) -> tuple[Path, str] | None:
84
+ """Locate a checkout: the current tree if it is one, otherwise the cached tarball."""
85
+ directory = Path.cwd()
86
+ for _ in range(6):
87
+ if (directory / "docker-compose.yml").is_file() and (directory / "Dockerfile").is_file():
88
+ return directory, "local checkout"
89
+ if directory.parent == directory:
90
+ break
91
+ directory = directory.parent
92
+ if not allow_download:
93
+ return None
94
+
95
+ cache_root = (
96
+ Path(os.environ.get("XDG_CACHE_HOME") or (Path.home() / ".cache")) / "aether-browser"
97
+ )
98
+ target = cache_root / f"agent-browser-{SOURCE_TAG}"
99
+ if (target / "docker-compose.yml").is_file():
100
+ return target, f"cached source {_dim(str(target))}"
101
+
102
+ url = f"{REPO}/archive/refs/tags/{SOURCE_TAG}.tar.gz"
103
+ print(f" fetching source {_dim(url)}")
104
+ target.mkdir(parents=True, exist_ok=True)
105
+ tarball = cache_root / f"{SOURCE_TAG}.tar.gz"
106
+ fetch = _run(
107
+ ["curl", "-fsSL", "--proto", "=https", "--tlsv1.2", "-o", str(tarball), url],
108
+ )
109
+ if fetch.returncode != 0:
110
+ shutil.rmtree(target, ignore_errors=True)
111
+ print(fetch.stderr.strip())
112
+ return None
113
+ untar = _run(["tar", "-xzf", str(tarball), "-C", str(target), "--strip-components=1"])
114
+ tarball.unlink(missing_ok=True)
115
+ if untar.returncode != 0:
116
+ shutil.rmtree(target, ignore_errors=True)
117
+ print(untar.stderr.strip())
118
+ return None
119
+ return target, f"downloaded source {_dim(str(target))}"
120
+
121
+
122
+ def _preflight(*, for_up: bool) -> list[str]:
123
+ problems: list[str] = []
124
+
125
+ print(_bold("\nEnvironment"))
126
+ print(f" python {platform.python_version()}")
127
+ print(f" client aether-browser {__version__}")
128
+ print(f" os {sys.platform}")
129
+
130
+ print(_bold("\nRuntime prerequisites"))
131
+ if sys.platform.startswith("linux"):
132
+ _ok("Linux host")
133
+ else:
134
+ _bad(
135
+ f"the documented quickstart is Linux only (found {sys.platform}). It relies on "
136
+ "Docker host networking so both listeners stay on numeric loopback; Docker "
137
+ "Desktop is outside that contract."
138
+ )
139
+ problems.append(
140
+ "Run the container on a Linux host. The client library itself works on any "
141
+ "platform against a server you can reach."
142
+ )
143
+
144
+ docker = _version_of("docker")
145
+ if docker:
146
+ _ok(docker)
147
+ else:
148
+ _bad("docker not found on PATH")
149
+ problems.append("Install Docker Engine: https://docs.docker.com/engine/install/")
150
+
151
+ if docker:
152
+ compose = _compose_version()
153
+ if compose:
154
+ _ok(compose)
155
+ else:
156
+ _bad("docker compose v2 not available")
157
+ problems.append("Install the Docker Compose v2 plugin.")
158
+
159
+ info = _run(["docker", "info", "--format", "{{.ServerVersion}}"])
160
+ if info.returncode == 0:
161
+ _ok(f"docker daemon reachable (server {info.stdout.strip()})")
162
+ else:
163
+ _bad("docker daemon is not reachable")
164
+ problems.append("Start Docker, or add your user to the docker group and re-login.")
165
+
166
+ if for_up:
167
+ print(_bold("\nSource"))
168
+ found = _find_compose_dir(allow_download=False)
169
+ if found:
170
+ _ok(f"docker-compose.yml found in {found[1]} {_dim(str(found[0]))}")
171
+ else:
172
+ _warn(f"no checkout here; `up` will download {REPO} at {SOURCE_TAG}")
173
+
174
+ return problems
175
+
176
+
177
+ def _base_url() -> str:
178
+ return os.environ.get("AGENT_BROWSER_URL") or DEFAULT_BASE_URL
179
+
180
+
181
+ def _probe_health(base_url: str) -> tuple[dict[str, object] | None, AgentBrowserError | None]:
182
+ try:
183
+ return AgentBrowser(base_url=base_url, timeout=4.0).health(), None
184
+ except AgentBrowserError as error:
185
+ return None, error
186
+
187
+
188
+ def _cmd_doctor(_: list[str]) -> int:
189
+ problems = _preflight(for_up=True)
190
+
191
+ print(_bold("\nServer"))
192
+ base_url = _base_url()
193
+ health, error = _probe_health(base_url)
194
+ if health is not None:
195
+ _ok(f"{base_url} responding (version {health.get('version')})")
196
+ print(
197
+ f" browser_ready={health.get('browser_ready')} "
198
+ f"session_active={health.get('session_active')} "
199
+ f"slots_available={health.get('slots_available')}"
200
+ )
201
+ else:
202
+ _warn(f"{base_url} not responding yet {_dim(f'({error})')}")
203
+ print(f" start it with {_bold('aether-browser up')}")
204
+
205
+ print(_bold("\nTokens"))
206
+ if os.environ.get("AGENT_BROWSER_CONTROLLER_TOKEN"):
207
+ _ok("AGENT_BROWSER_CONTROLLER_TOKEN is set")
208
+ else:
209
+ _warn("AGENT_BROWSER_CONTROLLER_TOKEN unset (fine for strict loopback local mode)")
210
+
211
+ if problems:
212
+ print(_bold(_paint("31", "\nBlocking problems")))
213
+ for problem in problems:
214
+ print(f" - {problem}")
215
+ print()
216
+ return 1
217
+ print(_paint("32", "\nReady.\n"))
218
+ return 0
219
+
220
+
221
+ def _cmd_up(argv: list[str]) -> int:
222
+ problems = _preflight(for_up=False)
223
+ if problems:
224
+ print(_bold(_paint("31", "\nCannot start")))
225
+ for problem in problems:
226
+ print(f" - {problem}")
227
+ print()
228
+ return 1
229
+
230
+ print(_bold("\nSource"))
231
+ found = _find_compose_dir(allow_download=True)
232
+ if found is None:
233
+ print(_paint("31", "\nCould not obtain a source checkout to build from.\n"))
234
+ return 1
235
+ _ok(found[1])
236
+
237
+ print(_bold("\nBuilding and starting"))
238
+ print(
239
+ _dim(
240
+ " The first build installs a hash-locked Python environment and the current\n"
241
+ " Google Chrome Stable package, so it can take several minutes.\n"
242
+ )
243
+ )
244
+ detach = "--foreground" not in argv
245
+ command = ["docker", "compose", "up", "--build", *(["--detach"] if detach else [])]
246
+ result = subprocess.run(command, cwd=found[0], check=False) # noqa: S603
247
+ if result.returncode != 0:
248
+ return result.returncode
249
+
250
+ if detach:
251
+ print(f"\n API {DEFAULT_BASE_URL}/browser/health")
252
+ print(f" noVNC {NOVNC_URL}")
253
+ print(_dim("\n Stop with: aether-browser down\n"))
254
+ return 0
255
+
256
+
257
+ def _cmd_down(_: list[str]) -> int:
258
+ found = _find_compose_dir(allow_download=False)
259
+ if found is None:
260
+ print(
261
+ _paint("31", "No checkout found here. Run `down` from the directory you ran `up` in.")
262
+ )
263
+ return 1
264
+ command = ["docker", "compose", "down", "--volumes", "--remove-orphans"]
265
+ result = subprocess.run(command, cwd=found[0], check=False) # noqa: S603
266
+ return result.returncode
267
+
268
+
269
+ def _cmd_status(_: list[str]) -> int:
270
+ base_url = _base_url()
271
+ health, error = _probe_health(base_url)
272
+ if health is None:
273
+ print(_paint("31", f"Agent Browser is not responding at {base_url}"), file=sys.stderr)
274
+ if error is not None and error.code:
275
+ print(_dim(f" {error.code}"), file=sys.stderr)
276
+ return 1
277
+ print(json.dumps(health, indent=2))
278
+ return 0
279
+
280
+
281
+ def _cmd_open(_: list[str]) -> int:
282
+ opener = {"darwin": "open", "win32": "explorer"}.get(sys.platform, "xdg-open")
283
+ print(f"Opening {NOVNC_URL}")
284
+ if shutil.which(opener) is None or _run([opener, NOVNC_URL]).returncode != 0:
285
+ print(f"Open it manually: {NOVNC_URL}")
286
+ return 0
287
+
288
+
289
+ def _cmd_help(_: list[str]) -> int:
290
+ print(
291
+ f"""
292
+ {_bold("aether-browser")} {_dim(__version__)}
293
+ Client and CLI for Agent Browser by Aether AI.
294
+
295
+ {_bold("Usage")}
296
+ aether-browser <command>
297
+
298
+ {_bold("Commands")}
299
+ doctor Check Docker, platform, ports, and server health, and say what is wrong
300
+ up Build and start the runtime (Linux + Docker Compose v2; first build is slow)
301
+ down Stop the runtime and remove its volumes
302
+ status Print the server health document as JSON
303
+ open Open the live noVNC view in a browser
304
+ help Show this message
305
+
306
+ {_bold("Environment")}
307
+ AGENT_BROWSER_URL Server base URL (default {DEFAULT_BASE_URL})
308
+ AGENT_BROWSER_CONTROLLER_TOKEN Controller token, if the server runs authenticated
309
+ AGENT_BROWSER_OBSERVER_TOKEN Observer token
310
+
311
+ {_bold("Library")}
312
+ from aether_browser import AgentBrowser, session
313
+
314
+ {_dim(REPO)}
315
+ """
316
+ )
317
+ return 0
318
+
319
+
320
+ def _cmd_version(_: list[str]) -> int:
321
+ print(__version__)
322
+ return 0
323
+
324
+
325
+ COMMANDS = {
326
+ "doctor": _cmd_doctor,
327
+ "up": _cmd_up,
328
+ "down": _cmd_down,
329
+ "status": _cmd_status,
330
+ "open": _cmd_open,
331
+ "help": _cmd_help,
332
+ "--help": _cmd_help,
333
+ "-h": _cmd_help,
334
+ "--version": _cmd_version,
335
+ "-v": _cmd_version,
336
+ }
337
+
338
+
339
+ def main(argv: list[str] | None = None) -> int:
340
+ arguments = list(sys.argv[1:] if argv is None else argv)
341
+ command = arguments[0] if arguments else "help"
342
+ handler = COMMANDS.get(command)
343
+ if handler is None:
344
+ print(_paint("31", f"Unknown command: {command}"), file=sys.stderr)
345
+ _cmd_help([])
346
+ return 1
347
+ return handler(arguments[1:])
348
+
349
+
350
+ if __name__ == "__main__":
351
+ raise SystemExit(main())
File without changes
@@ -0,0 +1,153 @@
1
+ Metadata-Version: 2.4
2
+ Name: aether-browser
3
+ Version: 0.1.0
4
+ Summary: Client and CLI for Agent Browser by Aether AI: drive one self-hosted Chrome session over a closed HTTP API and watch or take over that same session through noVNC.
5
+ Project-URL: Homepage, https://github.com/AetherAI3/agent-browser
6
+ Project-URL: Repository, https://github.com/AetherAI3/agent-browser
7
+ Project-URL: Issues, https://github.com/AetherAI3/agent-browser/issues
8
+ Project-URL: Changelog, https://github.com/AetherAI3/agent-browser/blob/main/CHANGELOG.md
9
+ Author-email: Aether AI <aetherai@aethersystems.net>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agent-browser,ai-agents,automation,browser,chrome,computer-use,human-in-the-loop,novnc,self-hosted
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Internet :: WWW/HTTP :: Browsers
23
+ Classifier: Topic :: Software Development :: Testing
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+
28
+ # aether-browser
29
+
30
+ Client and CLI for **[Agent Browser](https://github.com/AetherAI3/agent-browser) by Aether AI** —
31
+ self-hosted Chrome for AI agents. Drive one browser session through a closed HTTP API, and watch or
32
+ take over that exact same session through noVNC.
33
+
34
+ ```bash
35
+ pip install aether-browser
36
+ ```
37
+
38
+ Zero runtime dependencies. Ships type hints (`py.typed`). Python 3.10+.
39
+
40
+ This is the Python sibling of the [`aether-browser` npm package](https://www.npmjs.com/package/aether-browser):
41
+ same name, same commands, same closed `v1` contract, released version for version.
42
+
43
+ ## Drive a session
44
+
45
+ The `session` context manager always attempts to end the session, including when the body raises,
46
+ so a crash cannot leave the single session slot occupied.
47
+
48
+ ```python
49
+ import os
50
+
51
+ from aether_browser import AgentBrowser, session
52
+
53
+ browser = AgentBrowser(
54
+ base_url="http://127.0.0.1:8092",
55
+ controller_token=os.environ["AGENT_BROWSER_CONTROLLER_TOKEN"],
56
+ )
57
+
58
+ with session(browser) as live:
59
+ print("watch it live at", live.view_url)
60
+
61
+ page = live.navigate("https://example.com")
62
+ print(page["title"], page["readable_text"][:200])
63
+
64
+ live.click(selector="#login")
65
+ live.type("ada", selector="#user")
66
+ live.press("Enter")
67
+
68
+ shot = live.snapshot()
69
+ print(f"{shot['vision_steps_remaining']} vision steps left")
70
+ ```
71
+
72
+ Connection settings fall back to `AGENT_BROWSER_URL`, `AGENT_BROWSER_CONTROLLER_TOKEN`, and
73
+ `AGENT_BROWSER_OBSERVER_TOKEN`, so `AgentBrowser()` works with no arguments in a configured
74
+ environment.
75
+
76
+ ## Two roles, kept separate
77
+
78
+ The server splits authority, and this client keeps that split visible in your code. The observer
79
+ token covers health and snapshot; the controller token is required to create, navigate, interact,
80
+ and end. Give a read-only caller only the observer token:
81
+
82
+ ```python
83
+ read_only = AgentBrowser(observer_token=os.environ["AGENT_BROWSER_OBSERVER_TOKEN"])
84
+ read_only.health()
85
+ ```
86
+
87
+ ## Errors
88
+
89
+ Failures raise `AgentBrowserError` carrying the server's stable `code`:
90
+
91
+ ```python
92
+ from aether_browser import AgentBrowserError
93
+
94
+ try:
95
+ browser.create_session()
96
+ except AgentBrowserError as error:
97
+ if error.is_capacity_reached:
98
+ print(f"busy; retry in {error.retry_after_seconds}s")
99
+ ```
100
+
101
+ Codes are `AUTH_REQUIRED`, `AUTH_FORBIDDEN`, `SESSION_CAPACITY_REACHED`, `SESSION_NOT_FOUND`,
102
+ `SESSION_EXPIRED`, `VISION_BUDGET_EXHAUSTED`, `INVALID_URL`, `DESTINATION_BLOCKED`,
103
+ `INVALID_INTERACTION`, `BROWSER_NOT_READY`, and `INTERNAL_ERROR`. A transport failure raises the
104
+ same class with `code` left `None`, so a refused connection is never mistaken for a refusal by the
105
+ server.
106
+
107
+ ## CLI
108
+
109
+ ```bash
110
+ aether-browser doctor # check Docker, platform, and server health; say what is wrong
111
+ aether-browser up # build and start the runtime
112
+ aether-browser status # print the health document
113
+ aether-browser open # open the live noVNC view
114
+ aether-browser down # stop and clean up
115
+ ```
116
+
117
+ Run `doctor` first. It checks the things that actually break a first run and tells you which one
118
+ failed, instead of leaving you to read a build log.
119
+
120
+ ### What `up` really does, and its limits
121
+
122
+ Agent Browser publishes **no Chrome-containing image** — distribution is source-only. So `up` builds
123
+ the image locally from source, and **the first build takes several minutes** because it installs a
124
+ hash-locked Python environment and the current Google Chrome Stable package. It uses the checkout
125
+ you are standing in if there is one, and otherwise downloads the matching tagged source tarball from
126
+ the official repository over HTTPS into your cache directory.
127
+
128
+ `up` requires **Linux** with Docker Compose v2. The documented quickstart uses Docker host
129
+ networking so both the API and the noVNC listeners stay bound to numeric loopback; Docker Desktop on
130
+ macOS and Windows is outside that contract, and `doctor` will tell you so rather than half-working.
131
+
132
+ **The library has no such limit.** It is plain HTTP over `urllib` and runs anywhere Python does —
133
+ point it at a server on a Linux host and drive it from macOS, Windows, or CI.
134
+
135
+ ## Security
136
+
137
+ The v0.1 noVNC surface is **unauthenticated** and intended for numeric loopback on a machine you
138
+ control. Treat every process and user that can reach that loopback interface as trusted with the
139
+ live browser view. Do not expose it through a tunnel, reverse proxy, or container bridge. See the
140
+ [security model](https://github.com/AetherAI3/agent-browser/blob/main/docs/SECURITY-MODEL.md).
141
+
142
+ The API is deliberately closed: `click`, `type`, `scroll`, and `press` are the only interactions,
143
+ and there is no arbitrary JavaScript, CDP, upload, clipboard, download, extension, shell,
144
+ filesystem, credential, or cookie field. This client cannot widen that surface, because the server
145
+ rejects unknown fields.
146
+
147
+ ## Status
148
+
149
+ `0.1.0` tracks Agent Browser `v0.1.0` and its `api_version: "v1"` contract, and is released
150
+ version for version with the npm client. Issues and design discussion are welcome on
151
+ [the repository](https://github.com/AetherAI3/agent-browser/issues).
152
+
153
+ Apache-2.0 · [Aether AI](https://github.com/AetherAI3)
@@ -0,0 +1,9 @@
1
+ aether_browser/__init__.py,sha256=fcZszZ8rg2Qbp74MeigGgDg0jGABKnVZHhivOSRUnVw,852
2
+ aether_browser/_client.py,sha256=0I2TbABLC0rk6s3fl_USbmo-mux75LXUnlliW4YOMfU,13470
3
+ aether_browser/cli.py,sha256=__XcC3IxyIBvIEZsMTYTqnOCXBV0TJ5rRaed2-O48ZQ,11310
4
+ aether_browser/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ aether_browser-0.1.0.dist-info/METADATA,sha256=IqwOHyr4QLCqKHCJkze2GNV1D9xcCu-5YEl-WHDiPwk,6450
6
+ aether_browser-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
7
+ aether_browser-0.1.0.dist-info/entry_points.txt,sha256=U3xPJAY6b5lJNGI7XwiNqUIJWuqfibTRC5KH8HkaXNM,59
8
+ aether_browser-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
9
+ aether_browser-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ aether-browser = aether_browser.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.