oya-browser 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. oya_browser-0.2.0/.gitignore +6 -0
  2. oya_browser-0.2.0/LICENSE +21 -0
  3. oya_browser-0.2.0/PKG-INFO +144 -0
  4. oya_browser-0.2.0/README.md +122 -0
  5. oya_browser-0.2.0/pyproject.toml +61 -0
  6. oya_browser-0.2.0/src/oya_browser/__init__.py +21 -0
  7. oya_browser-0.2.0/src/oya_browser/_browser_base.py +41 -0
  8. oya_browser-0.2.0/src/oya_browser/_config.py +83 -0
  9. oya_browser-0.2.0/src/oya_browser/_constants.py +68 -0
  10. oya_browser-0.2.0/src/oya_browser/_http.py +89 -0
  11. oya_browser-0.2.0/src/oya_browser/_namespace.py +36 -0
  12. oya_browser-0.2.0/src/oya_browser/_ops.py +196 -0
  13. oya_browser-0.2.0/src/oya_browser/_run_watch.py +95 -0
  14. oya_browser-0.2.0/src/oya_browser/_start.py +46 -0
  15. oya_browser-0.2.0/src/oya_browser/async_browser.py +185 -0
  16. oya_browser-0.2.0/src/oya_browser/browser.py +193 -0
  17. oya_browser-0.2.0/src/oya_browser/client.py +224 -0
  18. oya_browser-0.2.0/src/oya_browser/control.py +106 -0
  19. oya_browser-0.2.0/src/oya_browser/desktop.py +144 -0
  20. oya_browser-0.2.0/src/oya_browser/errors.py +12 -0
  21. oya_browser-0.2.0/src/oya_browser/file.py +62 -0
  22. oya_browser-0.2.0/src/oya_browser/key_config.py +21 -0
  23. oya_browser-0.2.0/src/oya_browser/persona_groups.py +35 -0
  24. oya_browser-0.2.0/src/oya_browser/personas.py +108 -0
  25. oya_browser-0.2.0/src/oya_browser/playbooks.py +54 -0
  26. oya_browser-0.2.0/src/oya_browser/proxies.py +31 -0
  27. oya_browser-0.2.0/src/oya_browser/py.typed +0 -0
  28. oya_browser-0.2.0/src/oya_browser/run.py +148 -0
  29. oya_browser-0.2.0/src/oya_browser/signup.py +70 -0
  30. oya_browser-0.2.0/tests/conftest.py +42 -0
  31. oya_browser-0.2.0/tests/test_async.py +27 -0
  32. oya_browser-0.2.0/tests/test_browser.py +115 -0
  33. oya_browser-0.2.0/tests/test_config.py +67 -0
  34. oya_browser-0.2.0/tests/test_desktop.py +91 -0
  35. oya_browser-0.2.0/tests/test_file.py +35 -0
  36. oya_browser-0.2.0/tests/test_namespaces.py +241 -0
  37. oya_browser-0.2.0/tests/test_run.py +181 -0
  38. oya_browser-0.2.0/tests/test_signup.py +87 -0
  39. oya_browser-0.2.0/tests/test_start.py +88 -0
  40. oya_browser-0.2.0/tests/test_tabs_and_links.py +152 -0
  41. oya_browser-0.2.0/uv.lock +2278 -0
@@ -0,0 +1,6 @@
1
+ .venv/
2
+ __pycache__/
3
+ .pytest_cache/
4
+ .mypy_cache/
5
+ .ruff_cache/
6
+ dist/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oya AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.5
2
+ Name: oya-browser
3
+ Version: 0.2.0
4
+ Summary: Real browsers for AI agents: start one on Oya Cloud or any provider, drive it, save a task as a playbook and replay it with no model. Plugs into browser-use over CDP.
5
+ Project-URL: Homepage, https://oyabrowser.com
6
+ Project-URL: Documentation, https://oyabrowser.com/docs/sdk
7
+ Project-URL: Repository, https://github.com/OyadotAI/oya-browser
8
+ Author-email: Oya <sales@getoya.ai>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: ai-agents,browser,browser-automation,browser-use,cdp,hipaa,mcp,playwright
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Internet :: WWW/HTTP :: Browsers
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: httpx>=0.27
19
+ Provides-Extra: browser-use
20
+ Requires-Dist: browser-use>=1.0; (python_version >= '3.11') and extra == 'browser-use'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # oya-browser
24
+
25
+ Real browsers for AI agents, from Python. Start a browser on Oya Cloud, your own infrastructure or any
26
+ provider your key routes to; drive it; have an agent do a task once; save it as a playbook; replay it with no
27
+ model. The Python twin of [`@oya-ai/browser`](https://www.npmjs.com/package/@oya-ai/browser).
28
+
29
+ ```bash
30
+ pip install oya-browser
31
+ export OYA_API_KEY=oya_... # from https://oyabrowser.com, or run `oya login` once
32
+ ```
33
+
34
+ ## Quickstart
35
+
36
+ ```python
37
+ from oya_browser import Oya
38
+
39
+ with Oya() as oya, oya.browser.start() as browser: # stopped when the block exits
40
+ browser.goto("https://httpbin.org/forms/post")
41
+ browser.ask("Order a large pizza for {{name}}, then submit the order", data={"name": "Ada"})
42
+ browser.to_playbook("pizza") # the run, saved as Playwright code
43
+ browser.play("pizza", {"name": "Alan"}) # replayed with no model
44
+ ```
45
+
46
+ Async, for agent frameworks:
47
+
48
+ ```python
49
+ from oya_browser import AsyncOya
50
+
51
+ async with AsyncOya() as oya:
52
+ async with await oya.browser.start() as browser:
53
+ print(await browser.ask("What is the title of https://example.com?"))
54
+ ```
55
+
56
+ ## browser-use on Oya
57
+
58
+ ```bash
59
+ pip install "oya-browser[browser-use]" # Python 3.11+
60
+ ```
61
+
62
+ ```python
63
+ from browser_use import Agent, ChatAnthropic
64
+ from oya_browser import AsyncOya
65
+
66
+ async with AsyncOya() as oya:
67
+ async with await oya.browser.start() as browser:
68
+ agent = Agent("Find the cheapest flight to Lisbon", llm=ChatAnthropic(model="claude-sonnet-5"),
69
+ browser=await browser.for_browser_use())
70
+ print((await agent.run()).final_result())
71
+ ```
72
+
73
+ browser-use drives the Oya browser over CDP, unchanged. Each Oya CDP URL carries a single-use ticket, so
74
+ `for_browser_use()` asks for a fresh one every time; use `fresh_cdp_url()` the same way for any other CDP tool.
75
+
76
+ ## Playwright, Puppeteer and Stagehand
77
+
78
+ `browser.cdp_url` (or `browser.fresh_cdp_url()`) is a CDP endpoint for Playwright's `connect_over_cdp`, and for
79
+ Stagehand v3's `cdpUrl`. Stagehand v4 runs inside its own browser extension, which Oya browsers do not load yet.
80
+
81
+ ## What a browser can do
82
+
83
+ | | |
84
+ |---|---|
85
+ | `goto(url)`, `analyze(format=None)`, `elements()` | Open a page; read it as TOON, markdown or JSONL with numbered elements |
86
+ | `click(id)`, `type(id, text)`, `press_key(key)`, `wait_for(selector)` | Act on elements by their number from `analyze()` |
87
+ | `scroll(direction, amount=None, at=None)` | Scroll the page, or aim at an inner scroller with `at=(x, y)` |
88
+ | `url()`, `tabs()`, `open_tab(url=None)`, `switch_tab(id)`, `close_tab(id)` | Tabs |
89
+ | `handle_dialog(accept, prompt_text=None)` | Answer a `confirm()` or `prompt()` holding the page |
90
+ | `ask(prompt, data=, secrets=)`, `extract(prompt, schema)` | A task in plain language; `secrets` are typed but never shown to the model |
91
+ | `to_playbook(name)`, `play(name, data, auto_heal=True)` | Save the last task; replay it with no model, repairing a step a page changed |
92
+ | `submit(prompt)` or `submit(playbook=...)` | A background run with `on_success`, `on_failure`, `on_human_attention`, `on_healed` callbacks |
93
+ | `live_view_url()`, `live_stream_url()`, `share_url(control=False)`, `revoke_share(id)` | Watch it, embed its frames, or hand a person a scoped, expiring link |
94
+ | `solve_captcha()`, `complete_mfa()`, `screenshot()`, `status()`, `stop()` | |
95
+
96
+ `oya.browser.start(captcha="auto")` makes every `goto()` clear a CAPTCHA, raising `OyaError` (409) when one needs
97
+ a person.
98
+
99
+ `submit()` on `AsyncOya` polls in the background as soon as it returns; `await run.done` for the result. The
100
+ sync client has no background to poll in without a thread, so `run.wait()` polls, fires the same callbacks in the
101
+ same order, and returns the result or raises. Answer an attention request with `request["respond"]()`.
102
+
103
+ ```python
104
+ run = browser.submit(playbook="prior-auth", data={"member": "M1"},
105
+ on_human_attention=lambda req: print("Needs you:", req["liveViewUrl"]))
106
+ result = run.wait()
107
+ ```
108
+
109
+ Files ride in `data`: `browser.ask("Attach my resume", data={"resume": file("cv.pdf")})`, up to
110
+ `MAX_FILE_BYTES` (10MB).
111
+
112
+ ## The client
113
+
114
+ | | |
115
+ |---|---|
116
+ | `oya.browser` | `start(persona=, provider=, name=, captcha=)`, `get(id)`, `list()`, `stop(ids)`, `stop_all()` |
117
+ | `oya.desktop` | `connect(persona=None)`: the person's own desktop browser with their logins, paired if needed |
118
+ | `Oya.signup(email)` | An agent's own key, saved to `~/.oya/config.json` |
119
+ | `oya.playbooks` | `list()`, `get(name)`, `promote(name)`, `export(name)`, `import_(doc, name=, overwrite=)`, `remove(name)` |
120
+ | `oya.llm` | `answer(question, values)`: the text for a free-text field in an exported playbook |
121
+ | `oya.personas` (`oya.profiles`) | `list`, `get`, `create`, `update`, `clone`, `preview`, `options`, `pin_proxy`, `remove`, `set_mfa`, `clear_mfa`, `set_credentials`, `credentials`, `clear_credentials`, `cookies`, `import_cookies`, `copy_cookies`, `clear_cookies` |
122
+ | `oya.persona_groups` (`oya.profile_groups`) | `list`, `create`, `update`, `remove` |
123
+ | `oya.proxies` | `list`, `create`, `remove`, `check` |
124
+ | `oya.control` | Sessions, takeover, recovery, events, service credentials, members, webhooks |
125
+ | `oya.config` | `get()`, `set(values)`: this key's model, provider and solver settings |
126
+ | `oya.usage()` | Usage on this key |
127
+
128
+ Results are the server's JSON as plain dicts. On `AsyncOya` the same calls are awaited.
129
+
130
+ Every failure raises `OyaError` with the server's message, `status` and `body`.
131
+
132
+ ## Configuration
133
+
134
+ The key and address come from the arguments (`Oya(api_key=..., base_url=...)`), then `OYA_API_KEY` and
135
+ `OYA_BASE_URL`, then the key `oya login` saved in `~/.oya/config.json`, the same order as the TypeScript SDK.
136
+
137
+ ## HIPAA
138
+
139
+ HIPAA mode runs on Oya Cloud (BAA on request) or self-hosted in your own cloud. See
140
+ [oyabrowser.com/baa](https://oyabrowser.com/baa).
141
+
142
+ ## License
143
+
144
+ MIT
@@ -0,0 +1,122 @@
1
+ # oya-browser
2
+
3
+ Real browsers for AI agents, from Python. Start a browser on Oya Cloud, your own infrastructure or any
4
+ provider your key routes to; drive it; have an agent do a task once; save it as a playbook; replay it with no
5
+ model. The Python twin of [`@oya-ai/browser`](https://www.npmjs.com/package/@oya-ai/browser).
6
+
7
+ ```bash
8
+ pip install oya-browser
9
+ export OYA_API_KEY=oya_... # from https://oyabrowser.com, or run `oya login` once
10
+ ```
11
+
12
+ ## Quickstart
13
+
14
+ ```python
15
+ from oya_browser import Oya
16
+
17
+ with Oya() as oya, oya.browser.start() as browser: # stopped when the block exits
18
+ browser.goto("https://httpbin.org/forms/post")
19
+ browser.ask("Order a large pizza for {{name}}, then submit the order", data={"name": "Ada"})
20
+ browser.to_playbook("pizza") # the run, saved as Playwright code
21
+ browser.play("pizza", {"name": "Alan"}) # replayed with no model
22
+ ```
23
+
24
+ Async, for agent frameworks:
25
+
26
+ ```python
27
+ from oya_browser import AsyncOya
28
+
29
+ async with AsyncOya() as oya:
30
+ async with await oya.browser.start() as browser:
31
+ print(await browser.ask("What is the title of https://example.com?"))
32
+ ```
33
+
34
+ ## browser-use on Oya
35
+
36
+ ```bash
37
+ pip install "oya-browser[browser-use]" # Python 3.11+
38
+ ```
39
+
40
+ ```python
41
+ from browser_use import Agent, ChatAnthropic
42
+ from oya_browser import AsyncOya
43
+
44
+ async with AsyncOya() as oya:
45
+ async with await oya.browser.start() as browser:
46
+ agent = Agent("Find the cheapest flight to Lisbon", llm=ChatAnthropic(model="claude-sonnet-5"),
47
+ browser=await browser.for_browser_use())
48
+ print((await agent.run()).final_result())
49
+ ```
50
+
51
+ browser-use drives the Oya browser over CDP, unchanged. Each Oya CDP URL carries a single-use ticket, so
52
+ `for_browser_use()` asks for a fresh one every time; use `fresh_cdp_url()` the same way for any other CDP tool.
53
+
54
+ ## Playwright, Puppeteer and Stagehand
55
+
56
+ `browser.cdp_url` (or `browser.fresh_cdp_url()`) is a CDP endpoint for Playwright's `connect_over_cdp`, and for
57
+ Stagehand v3's `cdpUrl`. Stagehand v4 runs inside its own browser extension, which Oya browsers do not load yet.
58
+
59
+ ## What a browser can do
60
+
61
+ | | |
62
+ |---|---|
63
+ | `goto(url)`, `analyze(format=None)`, `elements()` | Open a page; read it as TOON, markdown or JSONL with numbered elements |
64
+ | `click(id)`, `type(id, text)`, `press_key(key)`, `wait_for(selector)` | Act on elements by their number from `analyze()` |
65
+ | `scroll(direction, amount=None, at=None)` | Scroll the page, or aim at an inner scroller with `at=(x, y)` |
66
+ | `url()`, `tabs()`, `open_tab(url=None)`, `switch_tab(id)`, `close_tab(id)` | Tabs |
67
+ | `handle_dialog(accept, prompt_text=None)` | Answer a `confirm()` or `prompt()` holding the page |
68
+ | `ask(prompt, data=, secrets=)`, `extract(prompt, schema)` | A task in plain language; `secrets` are typed but never shown to the model |
69
+ | `to_playbook(name)`, `play(name, data, auto_heal=True)` | Save the last task; replay it with no model, repairing a step a page changed |
70
+ | `submit(prompt)` or `submit(playbook=...)` | A background run with `on_success`, `on_failure`, `on_human_attention`, `on_healed` callbacks |
71
+ | `live_view_url()`, `live_stream_url()`, `share_url(control=False)`, `revoke_share(id)` | Watch it, embed its frames, or hand a person a scoped, expiring link |
72
+ | `solve_captcha()`, `complete_mfa()`, `screenshot()`, `status()`, `stop()` | |
73
+
74
+ `oya.browser.start(captcha="auto")` makes every `goto()` clear a CAPTCHA, raising `OyaError` (409) when one needs
75
+ a person.
76
+
77
+ `submit()` on `AsyncOya` polls in the background as soon as it returns; `await run.done` for the result. The
78
+ sync client has no background to poll in without a thread, so `run.wait()` polls, fires the same callbacks in the
79
+ same order, and returns the result or raises. Answer an attention request with `request["respond"]()`.
80
+
81
+ ```python
82
+ run = browser.submit(playbook="prior-auth", data={"member": "M1"},
83
+ on_human_attention=lambda req: print("Needs you:", req["liveViewUrl"]))
84
+ result = run.wait()
85
+ ```
86
+
87
+ Files ride in `data`: `browser.ask("Attach my resume", data={"resume": file("cv.pdf")})`, up to
88
+ `MAX_FILE_BYTES` (10MB).
89
+
90
+ ## The client
91
+
92
+ | | |
93
+ |---|---|
94
+ | `oya.browser` | `start(persona=, provider=, name=, captcha=)`, `get(id)`, `list()`, `stop(ids)`, `stop_all()` |
95
+ | `oya.desktop` | `connect(persona=None)`: the person's own desktop browser with their logins, paired if needed |
96
+ | `Oya.signup(email)` | An agent's own key, saved to `~/.oya/config.json` |
97
+ | `oya.playbooks` | `list()`, `get(name)`, `promote(name)`, `export(name)`, `import_(doc, name=, overwrite=)`, `remove(name)` |
98
+ | `oya.llm` | `answer(question, values)`: the text for a free-text field in an exported playbook |
99
+ | `oya.personas` (`oya.profiles`) | `list`, `get`, `create`, `update`, `clone`, `preview`, `options`, `pin_proxy`, `remove`, `set_mfa`, `clear_mfa`, `set_credentials`, `credentials`, `clear_credentials`, `cookies`, `import_cookies`, `copy_cookies`, `clear_cookies` |
100
+ | `oya.persona_groups` (`oya.profile_groups`) | `list`, `create`, `update`, `remove` |
101
+ | `oya.proxies` | `list`, `create`, `remove`, `check` |
102
+ | `oya.control` | Sessions, takeover, recovery, events, service credentials, members, webhooks |
103
+ | `oya.config` | `get()`, `set(values)`: this key's model, provider and solver settings |
104
+ | `oya.usage()` | Usage on this key |
105
+
106
+ Results are the server's JSON as plain dicts. On `AsyncOya` the same calls are awaited.
107
+
108
+ Every failure raises `OyaError` with the server's message, `status` and `body`.
109
+
110
+ ## Configuration
111
+
112
+ The key and address come from the arguments (`Oya(api_key=..., base_url=...)`), then `OYA_API_KEY` and
113
+ `OYA_BASE_URL`, then the key `oya login` saved in `~/.oya/config.json`, the same order as the TypeScript SDK.
114
+
115
+ ## HIPAA
116
+
117
+ HIPAA mode runs on Oya Cloud (BAA on request) or self-hosted in your own cloud. See
118
+ [oyabrowser.com/baa](https://oyabrowser.com/baa).
119
+
120
+ ## License
121
+
122
+ MIT
@@ -0,0 +1,61 @@
1
+ # The Python SDK for Oya Browser: the TypeScript SDK's core (@oya-ai/browser) for Python agent stacks.
2
+ [project]
3
+ name = "oya-browser"
4
+ version = "0.2.0"
5
+ description = "Real browsers for AI agents: start one on Oya Cloud or any provider, drive it, save a task as a playbook and replay it with no model. Plugs into browser-use over CDP."
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ requires-python = ">=3.10"
10
+ authors = [{ name = "Oya", email = "sales@getoya.ai" }]
11
+ keywords = ["browser", "ai-agents", "browser-automation", "playwright", "cdp", "browser-use", "hipaa", "mcp"]
12
+ classifiers = [
13
+ "Programming Language :: Python :: 3",
14
+ "License :: OSI Approved :: MIT License",
15
+ "Topic :: Internet :: WWW/HTTP :: Browsers",
16
+ "Framework :: AsyncIO",
17
+ "Typing :: Typed",
18
+ ]
19
+ dependencies = ["httpx>=0.27"]
20
+
21
+ [project.optional-dependencies]
22
+ browser-use = ["browser-use>=1.0; python_version >= '3.11'"]
23
+
24
+ [project.urls]
25
+ Homepage = "https://oyabrowser.com"
26
+ Documentation = "https://oyabrowser.com/docs/sdk"
27
+ Repository = "https://github.com/OyadotAI/oya-browser"
28
+
29
+ [dependency-groups]
30
+ dev = ["pytest>=8", "pytest-asyncio>=0.24", "ruff>=0.6", "mypy>=1.11"]
31
+
32
+ [build-system]
33
+ requires = ["hatchling>=1.27"]
34
+ build-backend = "hatchling.build"
35
+
36
+ [tool.pytest.ini_options]
37
+ asyncio_mode = "auto"
38
+ asyncio_default_fixture_loop_scope = "function"
39
+ testpaths = ["tests"]
40
+
41
+ [tool.ruff]
42
+ line-length = 120
43
+ target-version = "py310"
44
+
45
+ [tool.ruff.lint]
46
+ select = ["E", "F", "I", "B", "UP", "D", "PLR2004"]
47
+ # Docstrings say what a thing is or does ("Closes the pool"), as the TypeScript doc comments do.
48
+ ignore = ["D203", "D213", "D105", "D107", "D401"]
49
+
50
+ [tool.ruff.lint.per-file-ignores]
51
+ "tests/*" = ["D", "PLR2004"]
52
+
53
+ [tool.mypy]
54
+ strict = true
55
+ packages = ["oya_browser"]
56
+ mypy_path = "src"
57
+
58
+ # browser-use is an optional extra, imported only by for_browser_use().
59
+ [[tool.mypy.overrides]]
60
+ module = ["browser_use", "browser_use.*"]
61
+ ignore_missing_imports = true
@@ -0,0 +1,21 @@
1
+ """oya-browser: real browsers for AI agents, from Python.
2
+
3
+ from oya_browser import Oya
4
+
5
+ with Oya() as oya, oya.browser.start() as browser:
6
+ browser.goto("https://example.com")
7
+ print(browser.ask("What is the page title?"))
8
+
9
+ With browser-use (pip install "oya-browser[browser-use]"):
10
+
11
+ agent = Agent(task, llm, browser=browser.for_browser_use())
12
+ """
13
+
14
+ from .browser import AsyncBrowser, Browser
15
+ from .client import AsyncOya, Oya
16
+ from .errors import OyaError
17
+ from .file import MAX_FILE_BYTES, file
18
+ from .run import AsyncRun, Run
19
+
20
+ __all__ = ["MAX_FILE_BYTES", "AsyncBrowser", "AsyncOya", "AsyncRun", "Browser", "Oya", "OyaError", "Run", "file"]
21
+ __version__ = "0.2.0"
@@ -0,0 +1,41 @@
1
+ """What Browser and AsyncBrowser share: what a browser knows about itself, its links, and the browser-use hand-off."""
2
+
3
+ from typing import Any
4
+
5
+ from . import _ops as ops
6
+ from ._http import AsyncHttp, Http
7
+
8
+ NO_CDP = "This browser has no CDP endpoint (its provider does not offer one), so browser-use cannot drive it."
9
+
10
+
11
+ def browser_use(cdp_url: str | None) -> Any:
12
+ """A browser_use.Browser on `cdp_url`; browser-use is an optional extra, imported only when asked for."""
13
+ if not cdp_url:
14
+ raise ValueError(NO_CDP)
15
+ try:
16
+ from browser_use import Browser as BrowserUseBrowser
17
+ except ImportError as e:
18
+ raise ImportError('browser-use is not installed: pip install "oya-browser[browser-use]"') from e
19
+ return BrowserUseBrowser(cdp_url=cdp_url)
20
+
21
+
22
+ class BrowserBase:
23
+ """What every browser knows about itself."""
24
+
25
+ def __init__(self, http: Http | AsyncHttp, info: dict[str, Any], auto_captcha: bool) -> None:
26
+ self.id: str = info["id"]
27
+ self.provider: str = info.get("provider") or "cdp"
28
+ self.persona: str = info.get("persona") or "default"
29
+ self.cdp_url: str | None = info.get("cdpUrl")
30
+ """Where Playwright, Puppeteer or browser-use connect; single use, see fresh_cdp_url()."""
31
+ self.reused: bool = info.get("reused") is True
32
+ """True when start() handed over a browser that was already running, such as the desktop app."""
33
+ self._auto_captcha = auto_captcha
34
+ self._base_url = http.origin.base_url
35
+
36
+ def live_view_url(self) -> str:
37
+ """Watch it work: the console, opened on this browser. Carries no credential; frames are live_stream_url()."""
38
+ return ops.live_view_url(self._base_url, self.id)
39
+
40
+ def __repr__(self) -> str:
41
+ return f"<{type(self).__name__} {self.id} on {self.provider}>"
@@ -0,0 +1,83 @@
1
+ """Where the key and the address come from: the option, then OYA_API_KEY / OYA_BASE_URL, then ~/.oya/config.json.
2
+
3
+ The same order as the TypeScript SDK and the `oya` CLI, so a key saved by `oya login` works here unchanged.
4
+ A saved key is only used for the deployment it was saved for, so a staging key never goes to production.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from urllib.parse import urlsplit
12
+
13
+ from ._constants import DEFAULT_BASE_URL, JSON_INDENT, PRIVATE_DIR, PRIVATE_FILE
14
+
15
+ NO_KEY = "No API key. Get one at https://oyabrowser.com, then set OYA_API_KEY or pass api_key=..."
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Origin:
20
+ """The key and the address the client calls."""
21
+
22
+ api_key: str
23
+ base_url: str
24
+
25
+
26
+ def config_file() -> Path:
27
+ """The CLI's config file: OYA_CONFIG_HOME, else ~/.oya, then config.json."""
28
+ return Path(os.environ.get("OYA_CONFIG_HOME") or str(Path.home() / ".oya")) / "config.json"
29
+
30
+
31
+ def _saved() -> dict[str, str]:
32
+ """The CLI's saved config, or nothing when there is none or it does not parse."""
33
+ try:
34
+ data = json.loads(config_file().read_text())
35
+ except (OSError, ValueError):
36
+ return {}
37
+ return {k: v for k, v in data.items() if isinstance(v, str)} if isinstance(data, dict) else {}
38
+
39
+
40
+ def _host(url: str) -> str:
41
+ """The deployment a URL belongs to: its host, port included."""
42
+ return urlsplit(url).netloc
43
+
44
+
45
+ def save_key(api_key: str, base_url: str) -> bool:
46
+ """Saves a key where `oya login` would, unless one is there already, owner-only; True when it wrote."""
47
+ if _saved().get("apiKey"):
48
+ return False
49
+ path = config_file()
50
+ path.parent.mkdir(mode=PRIVATE_DIR, parents=True, exist_ok=True)
51
+ text = json.dumps({**_saved(), "apiKey": api_key, "baseUrl": base_url}, indent=JSON_INDENT)
52
+ _write_private(path, text)
53
+ return True
54
+
55
+
56
+ def _write_private(path: Path, text: str) -> None:
57
+ """Writes `text` to `path` readable by its owner only, whatever was there before.
58
+
59
+ Opening the file itself with O_TRUNC would keep the mode of a file that already exists (a config left
60
+ world-readable stays so) and would follow a symlink planted at the path. So the key goes to a new file,
61
+ created exclusively and not through a link, and is renamed over the config in one step.
62
+ """
63
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
64
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), PRIVATE_FILE)
65
+ try:
66
+ with os.fdopen(fd, "w") as f:
67
+ f.write(text)
68
+ os.replace(tmp, path)
69
+ except BaseException:
70
+ tmp.unlink(missing_ok=True)
71
+ raise
72
+
73
+
74
+ def resolve(api_key: str | None = None, base_url: str | None = None) -> Origin:
75
+ """The key and address to use; raises without a key."""
76
+ saved = _saved()
77
+ address = (base_url or os.environ.get("OYA_BASE_URL") or saved.get("baseUrl") or DEFAULT_BASE_URL).rstrip("/")
78
+ saved_base = saved.get("baseUrl", DEFAULT_BASE_URL)
79
+ saved_key = saved.get("apiKey") if _host(saved_base) == _host(address) else None
80
+ key = (api_key or os.environ.get("OYA_API_KEY") or saved_key or "").strip()
81
+ if not key:
82
+ raise ValueError(NO_KEY)
83
+ return Origin(api_key=key, base_url=address)
@@ -0,0 +1,68 @@
1
+ """Every number the SDK uses, by name, in seconds: the same budgets as the TypeScript SDK's constants.ts."""
2
+
3
+ DEFAULT_BASE_URL = "https://oyabrowser.com"
4
+ """The hosted control plane, used when no option, environment variable or saved config names one."""
5
+
6
+ DEFAULT_TIMEOUT_S = 60.0
7
+ """A plain API call."""
8
+ START_TIMEOUT_S = 120.0
9
+ """Starting a browser: the start call itself, before any wait for a cloud browser to dial in."""
10
+ READY_TIMEOUT_S = 120.0
11
+ """How long a starting cloud browser has to dial in."""
12
+ READY_POLL_S = 2.0
13
+ """How often the fleet is checked while a cloud browser is starting."""
14
+ NAVIGATE_TIMEOUT_S = 120.0
15
+ """A navigation, which waits for the page to load."""
16
+ CHALLENGE_TIMEOUT_S = 180.0
17
+ """Solving a CAPTCHA or completing MFA."""
18
+ AGENT_TIMEOUT_S = 600.0
19
+ """An agent task or a playbook replay; the server keeps the connection alive meanwhile."""
20
+ PLAYBOOK_TIMEOUT_S = 120.0
21
+ """Saving a playbook."""
22
+ STOP_TIMEOUT_S = 60.0
23
+ """Stopping a browser, which destroys a cloud sandbox."""
24
+ WAIT_FOR_DEFAULT_S = 30.0
25
+ """How long wait_for() waits for a selector by default."""
26
+ WAIT_FOR_GRACE_S = 5.0
27
+ """Extra request time on top of wait_for()'s own timeout, so the server answers first."""
28
+ MS_PER_SECOND = 1000
29
+ """The API takes wait_for()'s timeout in milliseconds."""
30
+ AIMED_SCROLL_AMOUNT = 500
31
+ """Pixels an aimed scroll (scroll(at=...)) moves when no amount is given."""
32
+ SHARE_EXPIRES_S = 3600
33
+ """How long a share_url() link works by default."""
34
+ RUN_POLL_S = 2.0
35
+ """How often a submitted run is polled by default."""
36
+ MAX_RUN_POLL_ERRORS = 5
37
+ """Failed polls in a row before a run is reported as failed."""
38
+ DESKTOP_TIMEOUT_S = 300.0
39
+ """How long desktop.connect() waits for a person to click Connect (and allow the keychain prompt)."""
40
+ DESKTOP_PROVIDER = "oya-desktop"
41
+ """The provider the server names the Oya desktop app by."""
42
+ DESKTOP_DOWNLOAD_URL = "https://oyabrowser.com/#download"
43
+ """Where the desktop app is downloaded."""
44
+ BYTES_PER_MB = 1_048_576
45
+ """Bytes in a megabyte, for file limits and messages."""
46
+ MAX_FILE_MB = 10
47
+ """Largest task file: bigger and the server would refuse the body anyway."""
48
+ PRIVATE_FILE = 0o600
49
+ """Owner read and write only: the saved config holds a key."""
50
+ PRIVATE_DIR = 0o700
51
+ """~/.oya, created owner-only, so no other user can list or replace the key file in it."""
52
+ JSON_INDENT = 2
53
+ """Indent of the saved config, as `oya login` writes it."""
54
+
55
+ STATUS_UNKNOWN = 0
56
+ """A failure that was not an HTTP answer, such as a run that could not be polled."""
57
+ STATUS_NOT_FOUND = 404
58
+ """A session not recorded yet, which is fine while a browser starts."""
59
+ STATUS_CONFLICT = 409
60
+ """A browser whose creation ended."""
61
+ STATUS_UNPROCESSABLE = 422
62
+ """A command that ran and failed."""
63
+ STATUS_SERVER_ERROR = 500
64
+ """An agent failure reported without a status."""
65
+ STATUS_GATEWAY_TIMEOUT = 504
66
+ """A browser that did not dial in before its budget ran out."""
67
+ STATUS_BAD_REQUEST_FLOOR = 400
68
+ """Responses from here up are errors."""
@@ -0,0 +1,89 @@
1
+ """The one HTTP path every call takes, sync and async: the same headers, timeouts and error handling for both.
2
+
3
+ Errors come back as OyaError with the server's message, so a caller reads "Browser abc not found", not a status code.
4
+ """
5
+
6
+ from typing import Any
7
+ from urllib.parse import quote
8
+
9
+ import httpx
10
+
11
+ from ._config import Origin
12
+ from ._constants import DEFAULT_TIMEOUT_S, STATUS_BAD_REQUEST_FLOOR
13
+ from .errors import OyaError
14
+
15
+ USER_AGENT = "oya-browser-python"
16
+
17
+
18
+ def segment(value: object, field: str = "id") -> str:
19
+ """One path segment, encoded; refused when it is empty or would change the path ("/", "." or "..")."""
20
+ if not isinstance(value, str) or not value:
21
+ raise ValueError(f"{field} must be a non-empty string, not {value!r}")
22
+ if "/" in value or value in (".", ".."):
23
+ raise ValueError(f"{field} must be a single path segment, not {value!r}")
24
+ return quote(value, safe="")
25
+
26
+
27
+ def _headers(origin: Origin, extra: dict[str, str] | None) -> dict[str, str]:
28
+ """The key, the client name, and any per-call headers."""
29
+ return {"Authorization": f"Bearer {origin.api_key}", "User-Agent": USER_AGENT, **(extra or {})}
30
+
31
+
32
+ def _parsed(response: httpx.Response, call: str) -> Any:
33
+ """The JSON body, or an OyaError carrying the server's message when the call failed."""
34
+ try:
35
+ body: Any = response.json() if response.content else None
36
+ except ValueError:
37
+ body = response.text
38
+ if response.status_code >= STATUS_BAD_REQUEST_FLOOR:
39
+ message = body.get("error") if isinstance(body, dict) else None
40
+ raise OyaError(message or f"{call} failed ({response.status_code})", response.status_code, body)
41
+ return body
42
+
43
+
44
+ class Http:
45
+ """Synchronous calls to the control plane."""
46
+
47
+ def __init__(self, origin: Origin, client: httpx.Client | None = None, headers: dict[str, str] | None = None):
48
+ self.origin = origin
49
+ self._client = client or httpx.Client(base_url=origin.base_url)
50
+ self._extra = headers
51
+
52
+ def with_headers(self, headers: dict[str, str]) -> "Http":
53
+ """The same client sending `headers` on every call too."""
54
+ return Http(self.origin, self._client, {**(self._extra or {}), **headers})
55
+
56
+ def request(self, method: str, path: str, body: Any = None, timeout: float = DEFAULT_TIMEOUT_S, **kw: Any) -> Any:
57
+ """One call; returns the parsed JSON body."""
58
+ headers = _headers(self.origin, {**(self._extra or {}), **kw.get("headers", {})})
59
+ response = self._client.request(method, path, json=body, headers=headers, timeout=timeout)
60
+ return _parsed(response, f"{method} {path}")
61
+
62
+ def close(self) -> None:
63
+ """Closes the connection pool."""
64
+ self._client.close()
65
+
66
+
67
+ class AsyncHttp:
68
+ """Asynchronous calls to the control plane."""
69
+
70
+ def __init__(self, origin: Origin, client: httpx.AsyncClient | None = None, headers: dict[str, str] | None = None):
71
+ self.origin = origin
72
+ self._client = client or httpx.AsyncClient(base_url=origin.base_url)
73
+ self._extra = headers
74
+
75
+ def with_headers(self, headers: dict[str, str]) -> "AsyncHttp":
76
+ """The same client sending `headers` on every call too."""
77
+ return AsyncHttp(self.origin, self._client, {**(self._extra or {}), **headers})
78
+
79
+ async def request(
80
+ self, method: str, path: str, body: Any = None, timeout: float = DEFAULT_TIMEOUT_S, **kw: Any
81
+ ) -> Any:
82
+ """One call; returns the parsed JSON body."""
83
+ headers = _headers(self.origin, {**(self._extra or {}), **kw.get("headers", {})})
84
+ response = await self._client.request(method, path, json=body, headers=headers, timeout=timeout)
85
+ return _parsed(response, f"{method} {path}")
86
+
87
+ async def aclose(self) -> None:
88
+ """Closes the connection pool."""
89
+ await self._client.aclose()