humanless-browser-use 0.1.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.
@@ -0,0 +1,7 @@
1
+ node_modules/
2
+ dist/
3
+ .venv/
4
+ __pycache__/
5
+ *.pyc
6
+ .pytest_cache/
7
+ .env
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ninety Nine Oranges
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,111 @@
1
+ Metadata-Version: 2.5
2
+ Name: humanless-browser-use
3
+ Version: 0.1.0
4
+ Summary: Identity for AI agents: Humanless custom actions for browser-use 1.0. A real email inbox, parsed OTP codes and magic links, and TOTP 2FA for apps you own or are authorized to test.
5
+ Project-URL: Homepage, https://usehumanless.com
6
+ Project-URL: Documentation, https://usehumanless.com/docs
7
+ Project-URL: Source, https://github.com/usehumanless/integrations/tree/main/browser-agents/browser-use
8
+ Author-email: Ninety Nine Oranges <hello@usehumanless.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: 2fa,ai-agent,ai-agents,browser-use,email-verification,humanless,identity,identity for ai agents,otp,qa,totp
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Testing
16
+ Requires-Python: <3.15,>=3.11
17
+ Requires-Dist: browser-use==1.0.9
18
+ Requires-Dist: httpx==0.29.0
19
+ Requires-Dist: humanless==0.1.1
20
+ Description-Content-Type: text/markdown
21
+
22
+ # humanless-browser-use
23
+
24
+ Identity for AI agents: [Humanless](https://usehumanless.com) custom actions for
25
+ [browser-use](https://github.com/browser-use/browser-use) 1.0. Your browser agent gets a real email inbox, parsed OTP
26
+ codes and magic links, and TOTP 2FA (import a site's authenticator from its `otpauth://` URI or setup key), so it can
27
+ finish sign-up and login flows on apps you own or are authorized to test.
28
+
29
+ > **Use policy.** Use Humanless only for apps and accounts you own or are authorized to use or test. Never create
30
+ > bulk or fake accounts, and never use it to get around someone else's verification.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ pip install 'browser-use==1.0.9' 'humanless-browser-use==0.1.0'
36
+ # or, from this folder:
37
+ uv sync
38
+ ```
39
+
40
+ Set `HUMANLESS_API_KEY` (get one at https://api.usehumanless.com/app), or try it free with a 1-hour sandbox key:
41
+
42
+ ```bash
43
+ curl -X POST https://api.usehumanless.com/v1/sandbox/keys # email/TOTP only; receives mail only from the demo app
44
+ ```
45
+
46
+ ## How it plugs into browser-use
47
+
48
+ browser-use 1.0 custom tools are plain functions registered with `@tools.action('description')` on a `Tools`
49
+ object passed to `Agent(tools=...)`. `HumanlessActions.register(tools)` adds five of them. Names, descriptions and
50
+ parameter descriptions are the same as the Humanless MCP server's tools (`https://api.usehumanless.com/mcp`), so an
51
+ agent sees the same tools either way:
52
+
53
+ | action | what the model gets |
54
+ | --- | --- |
55
+ | `create_verification_identity(channels?, ttl_seconds?, declared_platforms?)` | `{identity_id, email, expires_at, totp_secret?}` |
56
+ | `wait_for_verification_code(identity_id, channel="any", timeout_seconds=30, since_unix_ms?)` | `{status: "received", code?, url?, sender, subject, received_at}` or `{status: "timeout", message}` |
57
+ | `enroll_authenticator(identity_id, otpauth_uri? \| secret?)` | `{authenticator_id, code, seconds_remaining, warning}` |
58
+ | `get_authenticator_code(identity_id, authenticator_id? \| issuer?)` | `{code, seconds_remaining, next_code?}` |
59
+ | `delete_verification_identity(identity_id)` | `{identity_id, status}` |
60
+
61
+ `wait_for_verification_code` returns whatever the next message holds: an OTP code, a magic link (`url`), or both.
62
+ Channels are `email` and `totp`; SMS is not exposed (coming soon).
63
+
64
+ ```python
65
+ from browser_use import Agent, Browser, Tools
66
+ from humanless_browser_use import SYSTEM_HINT, HumanlessActions
67
+
68
+ humanless = HumanlessActions() # HUMANLESS_API_KEY
69
+ tools = humanless.register(Tools())
70
+
71
+ agent = Agent(
72
+ "Sign up at https://api.usehumanless.com/demo/acme, verify the email and turn on 2FA.",
73
+ llm="anthropic:<model>", # or ChatOpenAI(...), ChatBrowserUse(), any Pydantic AI model
74
+ browser=Browser("chromium"),
75
+ tools=tools,
76
+ extend_system_message=SYSTEM_HINT, # tells the model when to use the actions
77
+ )
78
+ try:
79
+ history = await agent.run()
80
+ finally:
81
+ await humanless.cleanup() # deletes every identity the agent created
82
+ ```
83
+
84
+ ## Run the example
85
+
86
+ ```bash
87
+ uv run python examples/acme_signup.py # browser-use's default model (BROWSER_USE_API_KEY)
88
+ LLM=openai:<model> OPENAI_API_KEY=... uv run python examples/acme_signup.py
89
+ ```
90
+
91
+ Without `HUMANLESS_API_KEY` the example mints a sandbox key. The agent opens the Acme demo app, signs up with a fresh
92
+ identity, waits for the emailed code, reads the `otpauth://` URI on the 2FA page, imports it and types the TOTP code.
93
+
94
+ ## Tests
95
+
96
+ ```bash
97
+ uv run pytest # offline: registration + REST calls (mocked)
98
+ HUMANLESS_LIVE=1 uv run pytest # + live end-to-end (local Chrome + Humanless sandbox)
99
+ HUMANLESS_LIVE=1 HUMANLESS_SANDBOX_KEY=hl_live_... uv run pytest # reuse a sandbox key (5 keys/hour/IP)
100
+ ```
101
+
102
+ The live test runs a real `browser_use.Agent` with a real local Chrome against the Acme demo. The model is a scripted
103
+ Pydantic AI `FunctionModel` (browser-use 1.0 accepts any Pydantic AI model), so it needs no LLM key: it calls the
104
+ Humanless actions through the agent's own tool loop and drives the page through the agent's Python REPL, as an LLM
105
+ would.
106
+
107
+ ## Notes
108
+
109
+ - Requires Python 3.11-3.14 (browser-use 1.0.9). Pinned: `browser-use==1.0.9`, `humanless==0.1.1`, `httpx==0.29.0`.
110
+ - The authenticator routes are called over REST directly because the `humanless` 0.1.1 Python SDK does not expose them yet.
111
+ - An imported authenticator lives only as long as its identity: don't leave 2FA on at a site you need to sign in to later.
@@ -0,0 +1,90 @@
1
+ # humanless-browser-use
2
+
3
+ Identity for AI agents: [Humanless](https://usehumanless.com) custom actions for
4
+ [browser-use](https://github.com/browser-use/browser-use) 1.0. Your browser agent gets a real email inbox, parsed OTP
5
+ codes and magic links, and TOTP 2FA (import a site's authenticator from its `otpauth://` URI or setup key), so it can
6
+ finish sign-up and login flows on apps you own or are authorized to test.
7
+
8
+ > **Use policy.** Use Humanless only for apps and accounts you own or are authorized to use or test. Never create
9
+ > bulk or fake accounts, and never use it to get around someone else's verification.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install 'browser-use==1.0.9' 'humanless-browser-use==0.1.0'
15
+ # or, from this folder:
16
+ uv sync
17
+ ```
18
+
19
+ Set `HUMANLESS_API_KEY` (get one at https://api.usehumanless.com/app), or try it free with a 1-hour sandbox key:
20
+
21
+ ```bash
22
+ curl -X POST https://api.usehumanless.com/v1/sandbox/keys # email/TOTP only; receives mail only from the demo app
23
+ ```
24
+
25
+ ## How it plugs into browser-use
26
+
27
+ browser-use 1.0 custom tools are plain functions registered with `@tools.action('description')` on a `Tools`
28
+ object passed to `Agent(tools=...)`. `HumanlessActions.register(tools)` adds five of them. Names, descriptions and
29
+ parameter descriptions are the same as the Humanless MCP server's tools (`https://api.usehumanless.com/mcp`), so an
30
+ agent sees the same tools either way:
31
+
32
+ | action | what the model gets |
33
+ | --- | --- |
34
+ | `create_verification_identity(channels?, ttl_seconds?, declared_platforms?)` | `{identity_id, email, expires_at, totp_secret?}` |
35
+ | `wait_for_verification_code(identity_id, channel="any", timeout_seconds=30, since_unix_ms?)` | `{status: "received", code?, url?, sender, subject, received_at}` or `{status: "timeout", message}` |
36
+ | `enroll_authenticator(identity_id, otpauth_uri? \| secret?)` | `{authenticator_id, code, seconds_remaining, warning}` |
37
+ | `get_authenticator_code(identity_id, authenticator_id? \| issuer?)` | `{code, seconds_remaining, next_code?}` |
38
+ | `delete_verification_identity(identity_id)` | `{identity_id, status}` |
39
+
40
+ `wait_for_verification_code` returns whatever the next message holds: an OTP code, a magic link (`url`), or both.
41
+ Channels are `email` and `totp`; SMS is not exposed (coming soon).
42
+
43
+ ```python
44
+ from browser_use import Agent, Browser, Tools
45
+ from humanless_browser_use import SYSTEM_HINT, HumanlessActions
46
+
47
+ humanless = HumanlessActions() # HUMANLESS_API_KEY
48
+ tools = humanless.register(Tools())
49
+
50
+ agent = Agent(
51
+ "Sign up at https://api.usehumanless.com/demo/acme, verify the email and turn on 2FA.",
52
+ llm="anthropic:<model>", # or ChatOpenAI(...), ChatBrowserUse(), any Pydantic AI model
53
+ browser=Browser("chromium"),
54
+ tools=tools,
55
+ extend_system_message=SYSTEM_HINT, # tells the model when to use the actions
56
+ )
57
+ try:
58
+ history = await agent.run()
59
+ finally:
60
+ await humanless.cleanup() # deletes every identity the agent created
61
+ ```
62
+
63
+ ## Run the example
64
+
65
+ ```bash
66
+ uv run python examples/acme_signup.py # browser-use's default model (BROWSER_USE_API_KEY)
67
+ LLM=openai:<model> OPENAI_API_KEY=... uv run python examples/acme_signup.py
68
+ ```
69
+
70
+ Without `HUMANLESS_API_KEY` the example mints a sandbox key. The agent opens the Acme demo app, signs up with a fresh
71
+ identity, waits for the emailed code, reads the `otpauth://` URI on the 2FA page, imports it and types the TOTP code.
72
+
73
+ ## Tests
74
+
75
+ ```bash
76
+ uv run pytest # offline: registration + REST calls (mocked)
77
+ HUMANLESS_LIVE=1 uv run pytest # + live end-to-end (local Chrome + Humanless sandbox)
78
+ HUMANLESS_LIVE=1 HUMANLESS_SANDBOX_KEY=hl_live_... uv run pytest # reuse a sandbox key (5 keys/hour/IP)
79
+ ```
80
+
81
+ The live test runs a real `browser_use.Agent` with a real local Chrome against the Acme demo. The model is a scripted
82
+ Pydantic AI `FunctionModel` (browser-use 1.0 accepts any Pydantic AI model), so it needs no LLM key: it calls the
83
+ Humanless actions through the agent's own tool loop and drives the page through the agent's Python REPL, as an LLM
84
+ would.
85
+
86
+ ## Notes
87
+
88
+ - Requires Python 3.11-3.14 (browser-use 1.0.9). Pinned: `browser-use==1.0.9`, `humanless==0.1.1`, `httpx==0.29.0`.
89
+ - The authenticator routes are called over REST directly because the `humanless` 0.1.1 Python SDK does not expose them yet.
90
+ - An imported authenticator lives only as long as its identity: don't leave 2FA on at a site you need to sign in to later.
@@ -0,0 +1,50 @@
1
+ """browser-use + Humanless: an LLM agent signs up on the Acme demo app, verifies the email code and turns on 2FA.
2
+
3
+ uv run python examples/acme_signup.py
4
+
5
+ Model: browser-use's default (bu-4.0, needs BROWSER_USE_API_KEY or `browser-use login`), or set LLM to any model
6
+ string browser-use accepts, e.g. LLM=anthropic:<model> with ANTHROPIC_API_KEY, LLM=openai:<model> with OPENAI_API_KEY.
7
+ Humanless: uses HUMANLESS_API_KEY if set, else mints a free 1-hour sandbox key (it can only receive the demo's mail).
8
+
9
+ Use Humanless only for apps and accounts you own or are authorized to use or test.
10
+ """
11
+
12
+ import asyncio
13
+ import os
14
+
15
+ from browser_use import Agent, Browser, Tools
16
+
17
+ from humanless_browser_use import SYSTEM_HINT, HumanlessActions, create_sandbox_key
18
+
19
+ DEMO_URL = "https://api.usehumanless.com/demo/acme"
20
+
21
+ TASK = f"""Go to {DEMO_URL} and create an Acme account.
22
+ 1. Call create_verification_identity and sign up with the email it returns.
23
+ 2. After submitting, call wait_for_verification_code with the identity_id and enter the code.
24
+ 3. On the "Turn on two-factor authentication" page, read the otpauth:// URI shown on the page, call
25
+ enroll_authenticator with it, and enter the code it returns (if seconds_remaining is under 5, call
26
+ get_authenticator_code for a fresh one first).
27
+ 4. Finish with the final page's confirmation text."""
28
+
29
+
30
+ async def main() -> None:
31
+ api_key = os.environ.get("HUMANLESS_API_KEY") or (await create_sandbox_key())["key"]
32
+ humanless = HumanlessActions(api_key)
33
+ tools = humanless.register(Tools())
34
+
35
+ agent = Agent(
36
+ TASK,
37
+ llm=os.environ.get("LLM"), # None -> browser-use's default model
38
+ browser=Browser("chromium", headless=os.environ.get("HEADLESS", "1") == "1"),
39
+ tools=tools,
40
+ extend_system_message=SYSTEM_HINT,
41
+ )
42
+ try:
43
+ history = await agent.run(max_steps=25)
44
+ print(history.final_result())
45
+ finally:
46
+ await humanless.cleanup() # delete every identity the agent created
47
+
48
+
49
+ if __name__ == "__main__":
50
+ asyncio.run(main())
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["hatchling==1.33.0"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "humanless-browser-use"
7
+ version = "0.1.0"
8
+ description = "Identity for AI agents: Humanless custom actions for browser-use 1.0. A real email inbox, parsed OTP codes and magic links, and TOTP 2FA for apps you own or are authorized to test."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11,<3.15"
11
+ license = "MIT"
12
+ authors = [{ name = "Ninety Nine Oranges", email = "hello@usehumanless.com" }]
13
+ keywords = ["identity", "ai-agents", "identity for ai agents", "browser-use", "humanless", "otp", "2fa", "totp", "email-verification", "ai-agent", "qa"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Software Development :: Testing",
19
+ ]
20
+ dependencies = [
21
+ "browser-use==1.0.9",
22
+ "humanless==0.1.1",
23
+ "httpx==0.29.0",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://usehumanless.com"
28
+ Documentation = "https://usehumanless.com/docs"
29
+ Source = "https://github.com/usehumanless/integrations/tree/main/browser-agents/browser-use"
30
+
31
+ [dependency-groups]
32
+ dev = ["pytest==9.2.0", "pytest-asyncio==1.5.0"]
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["src/humanless_browser_use"]
36
+
37
+ [tool.hatch.build.targets.sdist]
38
+ include = ["src", "examples", "tests", "README.md", "LICENSE", "pyproject.toml"]
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+ asyncio_mode = "auto"
43
+ asyncio_default_fixture_loop_scope = "function"
44
+ markers = ["live: hits the real Humanless sandbox and starts a local Chrome (set HUMANLESS_LIVE=1)"]
@@ -0,0 +1,20 @@
1
+ """Humanless custom actions for browser-use 1.0.
2
+
3
+ from browser_use import Agent, Browser, Tools
4
+ from humanless_browser_use import HumanlessActions
5
+
6
+ tools = Tools()
7
+ humanless = HumanlessActions() # reads HUMANLESS_API_KEY
8
+ humanless.register(tools) # adds create_verification_identity, wait_for_verification_code, ...
9
+ try:
10
+ await Agent(task, llm=..., browser=Browser('chromium'), tools=tools).run()
11
+ finally:
12
+ await humanless.cleanup() # deletes every identity the agent created
13
+
14
+ Use Humanless only for apps and accounts you own or are authorized to use or test.
15
+ """
16
+
17
+ from ._actions import ACTION_NAMES, DESCRIPTIONS, SYSTEM_HINT, HumanlessActions, create_sandbox_key
18
+
19
+ __all__ = ["ACTION_NAMES", "DESCRIPTIONS", "SYSTEM_HINT", "HumanlessActions", "create_sandbox_key", "__version__"]
20
+ __version__ = "0.1.0"
@@ -0,0 +1,285 @@
1
+ """The actions themselves. Each one is a plain async function registered with ``@tools.action('...')``, the
2
+ browser-use 1.0 way to give the agent a custom tool (browser_use/tools.py: ``Tools.action``)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ from typing import Annotated, Any, Literal, Optional
8
+ from urllib.parse import quote
9
+
10
+ import httpx
11
+ from browser_use import Tools
12
+ from humanless import AsyncHumanless, HumanlessError, HumanlessTimeoutError
13
+ from pydantic import Field
14
+
15
+ DEFAULT_BASE_URL = "https://api.usehumanless.com"
16
+
17
+ ACTION_NAMES = (
18
+ "create_verification_identity",
19
+ "wait_for_verification_code",
20
+ "enroll_authenticator",
21
+ "get_authenticator_code",
22
+ "delete_verification_identity",
23
+ )
24
+
25
+ # Names and descriptions are copied verbatim from the Humanless MCP server (tools/list at
26
+ # https://api.usehumanless.com/mcp), so an agent sees the same tools over MCP and in browser-use.
27
+ DESCRIPTIONS = {
28
+ "create_verification_identity": (
29
+ "Create a disposable identity for testing sign-up, login or 2FA on an app you own or are authorized to test. "
30
+ 'Returns an email address (channel "email"), (channel "sms" is not available yet: SMS is coming soon) and/or a '
31
+ 'TOTP secret to enroll as an authenticator app (channel "totp"). Each identity lives up to 24 hours '
32
+ "(ttl_seconds). Use the returned identity_id with wait_for_verification_code. Delete it with "
33
+ "delete_verification_identity when finished. If the identity will receive codes from a major consumer platform "
34
+ "(Google, Apple, Microsoft, Meta, Amazon, ...) because it is the OWNER'S OWN account or test account there, pass "
35
+ 'declared_platforms (e.g. ["google"]); otherwise those codes can pause the identity pending an abuse review. '
36
+ "Never declare accounts the owner is not entitled to use."
37
+ ),
38
+ "wait_for_verification_code": (
39
+ "Block until the next email or SMS arrives for an identity, then return the extracted OTP code and/or magic "
40
+ 'link (shown as "OTP: <code>" / "Magic link: <url>"). Call it right after submitting the form that sends the '
41
+ "code; do not sleep first. Each message is returned once. If nothing arrives before the timeout the result says "
42
+ "so (not an error) and you can simply call again. Pass since_unix_ms (a time just before you triggered the "
43
+ "message) to also catch a message that arrived before you started waiting."
44
+ ),
45
+ "enroll_authenticator": (
46
+ 'Save a TOTP authenticator (the 2FA "authenticator app" setup) for an identity, on an account you own or are '
47
+ "authorized to test. Pass exactly one of: otpauth_uri (otpauth://totp/...), secret (the base32 setup key shown "
48
+ "under \"can't scan the code?\", with optional issuer/label/digits/period/algorithm) or qr_image_base64 (a "
49
+ "PNG/JPEG screenshot of the QR code, at most 2 MB). Returns authenticator_id and the current code to type into "
50
+ "the site's confirmation field. The secret is stored encrypted and is never shown again: later codes come from "
51
+ "get_authenticator_code. If the site then shows backup/recovery codes, save them with store_backup_codes."
52
+ ),
53
+ "get_authenticator_code": (
54
+ "Return the current code of an imported authenticator (pick it by authenticator_id, or by issuer when only one "
55
+ "matches) and how many seconds it stays valid. Near the end of a period next_code is included too."
56
+ ),
57
+ "delete_verification_identity": (
58
+ "Delete an identity when you are done with it (frees a slot under the plan's active-identity limit). Its email "
59
+ "address stops receiving mail. Safe to call more than once."
60
+ ),
61
+ }
62
+
63
+ #: MCP parameter descriptions (same source).
64
+ P_IDENTITY_ID = "identity_id returned by create_verification_identity."
65
+ P_IDENTITY_ID_AUTH = "identity_id the authenticator belongs to."
66
+ P_CHANNELS = 'Which channels to provision. Default ["email"].'
67
+ P_TTL = "How long the identity lives before it expires. Defaults to the server default."
68
+ P_DECLARED = (
69
+ "Consumer platforms (watch-list ids such as google, apple, microsoft, meta, amazon) on which this identity is the "
70
+ "account owner's OWN account or test account. Only with an account-wide key. Omit for your own apps."
71
+ )
72
+ P_WAIT_CHANNEL = 'Only wait for this channel. Default "any".'
73
+ P_TIMEOUT = "Seconds to wait (default 30, max 60)."
74
+ P_SINCE = "Only return messages received at or after this Unix time in milliseconds."
75
+ P_OTPAUTH = "otpauth://totp/Issuer:account?secret=...&issuer=..."
76
+ P_SECRET = "Base32 setup key (spaces and lower case are fine)."
77
+ P_AUTH_ID = "From enroll_authenticator or list_authenticators."
78
+ P_ISSUER_ALT = 'Alternative to authenticator_id, e.g. "GitHub".'
79
+
80
+ WAIT_DEFAULT_TIMEOUT_S = 30
81
+ WAIT_MAX_TIMEOUT_S = 60
82
+
83
+ #: Appended to the task so the model knows when to reach for the actions (pass to Agent(extend_system_message=...)).
84
+ SYSTEM_HINT = (
85
+ "You have Humanless actions for sign-up, login and 2FA on apps the user owns or is authorized to test. Flow: "
86
+ "create_verification_identity -> fill the form with its email -> wait_for_verification_code with the identity_id "
87
+ "(returns the OTP code and/or magic link; never guess codes) -> when a site shows a 2FA QR code, read its "
88
+ "otpauth:// URI or setup key from the page and call enroll_authenticator, then type the code it returns; later "
89
+ "call get_authenticator_code -> delete_verification_identity when done."
90
+ )
91
+
92
+
93
+ def _base_url(base_url: Optional[str]) -> str:
94
+ url = base_url or os.environ.get("HUMANLESS_BASE_URL") or DEFAULT_BASE_URL
95
+ url = url.rstrip("/")
96
+ return url[:-3] if url.lower().endswith("/v1") else url
97
+
98
+
99
+ async def create_sandbox_key(base_url: Optional[str] = None) -> dict[str, Any]:
100
+ """POST /v1/sandbox/keys: a free 1-hour demo key (email/TOTP only; receives mail only from the Acme demo app)."""
101
+ async with httpx.AsyncClient(timeout=30) as http:
102
+ res = await http.post(f"{_base_url(base_url)}/v1/sandbox/keys", headers={"accept": "application/json"})
103
+ if res.status_code >= 400:
104
+ try:
105
+ err = res.json().get("error", {})
106
+ except ValueError:
107
+ err = {}
108
+ raise HumanlessError(res.status_code, err.get("code", f"http_{res.status_code}"), err.get("message", res.text[:200]))
109
+ return res.json()
110
+
111
+
112
+ class HumanlessActions:
113
+ """Holds the Humanless key and the identities this run created, so ``cleanup()`` can delete them."""
114
+
115
+ def __init__(self, api_key: Optional[str] = None, *, base_url: Optional[str] = None, default_ttl_seconds: int = 3600):
116
+ key = api_key or os.environ.get("HUMANLESS_API_KEY")
117
+ if not key:
118
+ raise ValueError("HumanlessActions: pass api_key=... or set HUMANLESS_API_KEY")
119
+ self._api_key = key
120
+ self.base_url = _base_url(base_url)
121
+ self.default_ttl_seconds = default_ttl_seconds
122
+ self.created: list[str] = []
123
+
124
+ # A fresh client per call: browser-use may run actions on a different event loop than the one this object was
125
+ # built on (Agent.run_sync), and an httpx.AsyncClient must not cross loops.
126
+ def _client(self) -> AsyncHumanless:
127
+ return AsyncHumanless(self._api_key, base_url=self.base_url)
128
+
129
+ async def _raw(self, method: str, path: str, body: Any = None) -> Any:
130
+ """Authenticator routes (not in humanless==0.1.1's Python SDK yet)."""
131
+ async with httpx.AsyncClient(timeout=30) as http:
132
+ res = await http.request(
133
+ method,
134
+ f"{self.base_url}{path}",
135
+ headers={"authorization": f"Bearer {self._api_key}", "accept": "application/json"},
136
+ json=body,
137
+ )
138
+ data = res.json() if res.content else None
139
+ if res.status_code >= 400:
140
+ err = (data or {}).get("error", {}) if isinstance(data, dict) else {}
141
+ raise HumanlessError(res.status_code, err.get("code", f"http_{res.status_code}"), err.get("message", res.text[:200]))
142
+ return data
143
+
144
+
145
+ # ------------------------------------------------------------------ actions (plain functions the model calls)
146
+
147
+ async def create_verification_identity(
148
+ self,
149
+ channels: Optional[list[str]] = None,
150
+ ttl_seconds: Optional[int] = None,
151
+ declared_platforms: Optional[list[str]] = None,
152
+ ) -> dict[str, Any]:
153
+ chans = list(channels or ["email"])
154
+ bad = [c for c in chans if c not in ("email", "totp")]
155
+ if bad:
156
+ return {"error": f"Unsupported channel(s) {bad}: use \"email\" and/or \"totp\" (SMS is coming soon)."}
157
+ body: dict[str, Any] = {"channels": chans, "ttl_seconds": ttl_seconds or self.default_ttl_seconds}
158
+ if declared_platforms:
159
+ body["declared_platforms"] = list(declared_platforms)
160
+ idn = await self._raw("POST", "/v1/identities", body)
161
+ self.created.append(idn["identity_id"])
162
+ out = {"identity_id": idn["identity_id"], "email": idn.get("email"), "expires_at": idn.get("expires_at")}
163
+ if idn.get("totp_secret"):
164
+ out["totp_secret"] = idn["totp_secret"]
165
+ return out
166
+
167
+ async def wait_for_verification_code(
168
+ self,
169
+ identity_id: str,
170
+ channel: str = "any",
171
+ timeout_seconds: float = WAIT_DEFAULT_TIMEOUT_S,
172
+ since_unix_ms: Optional[int] = None,
173
+ ) -> dict[str, Any]:
174
+ timeout = min(max(float(timeout_seconds), 0.0), float(WAIT_MAX_TIMEOUT_S))
175
+ try:
176
+ async with self._client() as hl:
177
+ m = await hl.wait_for_message(identity_id, channel=channel, timeout=timeout, since=since_unix_ms) # type: ignore[arg-type]
178
+ except HumanlessTimeoutError:
179
+ return {
180
+ "status": "timeout",
181
+ "identity_id": identity_id,
182
+ "message": f"No message arrived within {timeout:g} seconds. Nothing is wrong yet: make sure the form "
183
+ "was submitted, then call wait_for_verification_code again with the same identity_id.",
184
+ }
185
+ out: dict[str, Any] = {"status": "received", "identity_id": identity_id}
186
+ if m.get("code"):
187
+ out["code"] = m["code"]
188
+ if m.get("url"):
189
+ out["url"] = m["url"]
190
+ out.update({"sender": m.get("sender"), "subject": m.get("subject"), "received_at": m.get("received_at")})
191
+ if not m.get("code") and not m.get("url"):
192
+ out["snippet"] = m.get("raw_snippet")
193
+ return out
194
+
195
+ async def enroll_authenticator(
196
+ self, identity_id: str, otpauth_uri: Optional[str] = None, secret: Optional[str] = None
197
+ ) -> dict[str, Any]:
198
+ if bool(otpauth_uri) == bool(secret):
199
+ return {"error": "Pass exactly one of otpauth_uri (otpauth://totp/...) or secret (the base32 setup key)."}
200
+ body = {"otpauth_uri": otpauth_uri} if otpauth_uri else {"secret": secret}
201
+ r = await self._raw("POST", f"/v1/identities/{quote(identity_id, safe='')}/authenticators", body)
202
+ return {
203
+ "authenticator_id": r["authenticator_id"],
204
+ "code": r["current_code"],
205
+ "seconds_remaining": r["seconds_remaining"],
206
+ "warning": r.get("warning"),
207
+ }
208
+
209
+ async def get_authenticator_code(
210
+ self, identity_id: str, authenticator_id: Optional[str] = None, issuer: Optional[str] = None
211
+ ) -> dict[str, Any]:
212
+ base = f"/v1/identities/{quote(identity_id, safe='')}"
213
+ if authenticator_id:
214
+ r = await self._raw("GET", f"{base}/authenticators/{quote(authenticator_id, safe='')}/code")
215
+ elif issuer:
216
+ r = await self._raw("GET", f"{base}/totp?issuer={quote(issuer, safe='')}")
217
+ else:
218
+ return {"error": "Pass authenticator_id (from enroll_authenticator) or issuer."}
219
+ out = {"code": r["code"], "seconds_remaining": r["seconds_remaining"]}
220
+ if r.get("next_code"):
221
+ out["next_code"] = r["next_code"] # use it if seconds_remaining is too short to type the code
222
+ return out
223
+
224
+ async def delete_verification_identity(self, identity_id: str) -> dict[str, Any]:
225
+ async with self._client() as hl:
226
+ r = await hl.delete_identity(identity_id)
227
+ if identity_id in self.created:
228
+ self.created.remove(identity_id)
229
+ return dict(r)
230
+
231
+ async def cleanup(self) -> None:
232
+ """Delete every identity this object created (idempotent; call it in ``finally``)."""
233
+ for identity_id in list(self.created):
234
+ try:
235
+ await self.delete_verification_identity(identity_id)
236
+ except HumanlessError:
237
+ pass
238
+
239
+ # ------------------------------------------------------------------ browser-use wiring
240
+
241
+ def register(self, tools: Tools) -> Tools:
242
+ """Register every action on a browser-use ``Tools`` and return it. The function name is the tool name the
243
+ model sees; the description string is what it reads (both match the Humanless MCP server)."""
244
+ me = self
245
+
246
+ @tools.action(DESCRIPTIONS["create_verification_identity"])
247
+ async def create_verification_identity(
248
+ channels: Annotated[Optional[list[Literal["email", "totp"]]], Field(description=P_CHANNELS)] = None,
249
+ ttl_seconds: Annotated[Optional[int], Field(description=P_TTL)] = None,
250
+ declared_platforms: Annotated[Optional[list[str]], Field(description=P_DECLARED)] = None,
251
+ ) -> dict:
252
+ return await me.create_verification_identity(
253
+ list(channels) if channels else None, ttl_seconds, declared_platforms
254
+ )
255
+
256
+ @tools.action(DESCRIPTIONS["wait_for_verification_code"])
257
+ async def wait_for_verification_code(
258
+ identity_id: Annotated[str, Field(description=P_IDENTITY_ID)],
259
+ channel: Annotated[Literal["any", "email"], Field(description=P_WAIT_CHANNEL)] = "any",
260
+ timeout_seconds: Annotated[float, Field(description=P_TIMEOUT, ge=0, le=WAIT_MAX_TIMEOUT_S)] = WAIT_DEFAULT_TIMEOUT_S,
261
+ since_unix_ms: Annotated[Optional[int], Field(description=P_SINCE, ge=0)] = None,
262
+ ) -> dict:
263
+ return await me.wait_for_verification_code(identity_id, channel, timeout_seconds, since_unix_ms)
264
+
265
+ @tools.action(DESCRIPTIONS["enroll_authenticator"])
266
+ async def enroll_authenticator(
267
+ identity_id: Annotated[str, Field(description=P_IDENTITY_ID_AUTH)],
268
+ otpauth_uri: Annotated[Optional[str], Field(description=P_OTPAUTH)] = None,
269
+ secret: Annotated[Optional[str], Field(description=P_SECRET)] = None,
270
+ ) -> dict:
271
+ return await me.enroll_authenticator(identity_id, otpauth_uri, secret)
272
+
273
+ @tools.action(DESCRIPTIONS["get_authenticator_code"])
274
+ async def get_authenticator_code(
275
+ identity_id: Annotated[str, Field(description=P_IDENTITY_ID_AUTH)],
276
+ authenticator_id: Annotated[Optional[str], Field(description=P_AUTH_ID)] = None,
277
+ issuer: Annotated[Optional[str], Field(description=P_ISSUER_ALT)] = None,
278
+ ) -> dict:
279
+ return await me.get_authenticator_code(identity_id, authenticator_id, issuer)
280
+
281
+ @tools.action(DESCRIPTIONS["delete_verification_identity"])
282
+ async def delete_verification_identity(identity_id: Annotated[str, Field(description=P_IDENTITY_ID)]) -> dict:
283
+ return await me.delete_verification_identity(identity_id)
284
+
285
+ return tools
@@ -0,0 +1,111 @@
1
+ """Offline tests: the actions register on a real browser-use Tools and call the Humanless REST API correctly."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import httpx
7
+ import pytest
8
+ from browser_use import Tools
9
+
10
+ from humanless_browser_use import ACTION_NAMES, DESCRIPTIONS, HumanlessActions
11
+
12
+
13
+
14
+ def test_registers_every_action_on_browser_use_tools():
15
+ tools = HumanlessActions("hl_live_test").register(Tools())
16
+ assert sorted(t.name for t in tools.functions) == sorted(ACTION_NAMES)
17
+ by_name = {t.name: t for t in tools.functions}
18
+ assert "otpauth" in by_name["enroll_authenticator"].description
19
+ # the JSON schema the model sees comes from the function signature
20
+ params = by_name["wait_for_verification_code"].function_schema.json_schema
21
+ assert params["required"] == ["identity_id"]
22
+ assert set(params["properties"]) == {"identity_id", "channel", "timeout_seconds", "since_unix_ms"}
23
+ assert params["properties"]["identity_id"]["description"] == "identity_id returned by create_verification_identity."
24
+ create = by_name["create_verification_identity"].function_schema.json_schema
25
+ assert "declared_platforms" in create["properties"]
26
+
27
+
28
+ MCP_SNAPSHOT = Path(__file__).resolve().parents[3] / "mcp-tools.json"
29
+
30
+
31
+ @pytest.mark.skipif(not MCP_SNAPSHOT.exists(), reason="mcp-tools.json snapshot lives at the repo root")
32
+ def test_names_and_descriptions_match_the_mcp_server():
33
+ mcp = {t["name"]: t for t in json.loads(MCP_SNAPSHOT.read_text())["tools"]}
34
+ tools = HumanlessActions("hl_live_test").register(Tools())
35
+ for t in tools.functions:
36
+ assert t.name in mcp, t.name
37
+ assert t.description == mcp[t.name]["description"], t.name
38
+ assert DESCRIPTIONS[t.name] == mcp[t.name]["description"]
39
+ props = t.function_schema.json_schema["properties"]
40
+ for param, spec in props.items():
41
+ assert spec.get("description") == mcp[t.name]["params"][param], (t.name, param)
42
+
43
+
44
+ def test_requires_a_key(monkeypatch):
45
+ monkeypatch.delenv("HUMANLESS_API_KEY", raising=False)
46
+ with pytest.raises(ValueError):
47
+ HumanlessActions()
48
+
49
+
50
+ class FakeApi:
51
+ def __init__(self):
52
+ self.calls = []
53
+
54
+ def __call__(self, request: httpx.Request) -> httpx.Response:
55
+ self.calls.append((request.method, request.url.path, request.content and json.loads(request.content)))
56
+ assert request.headers["authorization"] == "Bearer hl_live_test"
57
+ p = request.url.path
58
+ if request.method == "POST" and p == "/v1/identities":
59
+ return httpx.Response(200, json={"identity_id": "id1", "email": "a@x.test", "expires_at": "t"})
60
+ if p == "/v1/identities/id1/wait":
61
+ return httpx.Response(200, json={"type": "otp", "code": "123456", "url": "https://x.test/l", "channel": "email",
62
+ "sender": "demo@x", "subject": "Code", "received_at": "2026-01-01T00:00:00Z",
63
+ "raw_snippet": ""})
64
+ if request.method == "POST" and p == "/v1/identities/id1/authenticators":
65
+ return httpx.Response(200, json={"authenticator_id": "au1", "current_code": "654321", "seconds_remaining": 20,
66
+ "warning": "w"})
67
+ if p == "/v1/identities/id1/authenticators/au1/code":
68
+ return httpx.Response(200, json={"authenticator_id": "au1", "code": "111111", "seconds_remaining": 5,
69
+ "next_code": "222222"})
70
+ if request.method == "DELETE" and p == "/v1/identities/id1":
71
+ return httpx.Response(200, json={"identity_id": "id1", "status": "deleted"})
72
+ return httpx.Response(404, json={"error": {"code": "not_found", "message": p}})
73
+
74
+
75
+ @pytest.fixture
76
+ def api(monkeypatch):
77
+ fake = FakeApi()
78
+ real = httpx.AsyncClient.__init__
79
+
80
+ def patched(self, *a, **kw):
81
+ kw["transport"] = httpx.MockTransport(fake)
82
+ real(self, *a, **kw)
83
+
84
+ monkeypatch.setattr(httpx.AsyncClient, "__init__", patched)
85
+ return fake
86
+
87
+
88
+ async def test_full_flow_against_mock_api(api):
89
+ hl = HumanlessActions("hl_live_test", base_url="https://api.test/v1")
90
+ idn = await hl.create_verification_identity(declared_platforms=["google"])
91
+ assert idn["email"] == "a@x.test" and hl.created == ["id1"]
92
+ assert api.calls[0][2] == {"channels": ["email"], "ttl_seconds": 3600, "declared_platforms": ["google"]}
93
+ got = await hl.wait_for_verification_code("id1")
94
+ assert got["status"] == "received" and got["code"] == "123456" and got["url"] == "https://x.test/l"
95
+ enrolled = await hl.enroll_authenticator("id1", otpauth_uri="otpauth://totp/A:b?secret=JBSWY3DPEHPK3PXP")
96
+ assert enrolled == {"authenticator_id": "au1", "code": "654321", "seconds_remaining": 20, "warning": "w"}
97
+ assert (await hl.get_authenticator_code("id1", "au1"))["next_code"] == "222222"
98
+ await hl.cleanup()
99
+ assert hl.created == []
100
+ assert any(m == "DELETE" and path == "/v1/identities/id1" for m, path, _ in api.calls)
101
+
102
+
103
+ async def test_sms_is_not_exposed():
104
+ hl = HumanlessActions("hl_live_test")
105
+ assert "error" in await hl.create_verification_identity(["sms"])
106
+
107
+
108
+ async def test_enroll_needs_exactly_one_source():
109
+ hl = HumanlessActions("hl_live_test")
110
+ assert "error" in await hl.enroll_authenticator("id1")
111
+ assert "error" in await hl.enroll_authenticator("id1", otpauth_uri="otpauth://x", secret="ABC")
@@ -0,0 +1,122 @@
1
+ """Live end-to-end test: a real browser-use Agent, a real local Chrome, the real Humanless sandbox and the Acme demo app.
2
+
3
+ No LLM key needed: the model is a scripted Pydantic AI FunctionModel (browser-use 1.0 accepts any Pydantic AI Model as
4
+ llm=...). It calls the Humanless actions through the agent's real tool loop and drives the browser through the agent's
5
+ own Python REPL, exactly as an LLM would. Run with: HUMANLESS_LIVE=1 uv run pytest -m live
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import re
11
+
12
+ import pytest
13
+ from pydantic_ai.messages import ModelMessage, ModelResponse, ToolCallPart, ToolReturnPart
14
+ from pydantic_ai.models.function import AgentInfo, FunctionModel
15
+
16
+ from browser_use import Agent, Browser, Tools
17
+ from humanless_browser_use import HumanlessActions, create_sandbox_key
18
+
19
+ DEMO = "https://api.usehumanless.com/demo/acme"
20
+
21
+ pytestmark = [
22
+ pytest.mark.live,
23
+ pytest.mark.skipif(os.environ.get("HUMANLESS_LIVE") != "1", reason="set HUMANLESS_LIVE=1 to run against the sandbox"),
24
+ ]
25
+
26
+
27
+ def _returns(messages: list[ModelMessage]) -> list[ToolReturnPart]:
28
+ return [p for m in messages for p in getattr(m, "parts", []) if isinstance(p, ToolReturnPart)]
29
+
30
+
31
+ def _text(part: ToolReturnPart) -> str:
32
+ c = part.content
33
+ if isinstance(c, list): # the python tool returns [text, *screenshots]
34
+ return "\n".join(x for x in c if isinstance(x, str))
35
+ if isinstance(c, dict):
36
+ return json.dumps(c, default=str)
37
+ return str(c)
38
+
39
+
40
+ def _submit_totp(code: str) -> str:
41
+ return (
42
+ f"fill_input('#totp', {code!r})\n"
43
+ "js(\"document.querySelector('button[type=submit]').click()\"); wait(1); wait_for_load()\n"
44
+ "print(js('document.querySelector(\"main\").innerText'))"
45
+ )
46
+
47
+
48
+ def scripted_model() -> FunctionModel:
49
+ """What a good LLM does on the Acme demo, one tool call per turn."""
50
+ state: dict = {}
51
+
52
+ def step(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
53
+ done = _returns(messages)
54
+ last = _text(done[-1]) if done else ""
55
+ n = len(done)
56
+ if os.environ.get("DEBUG_SCRIPT"):
57
+ print(f"[turn {n}] {last[:300]!r}")
58
+ if n == 0:
59
+ call = ToolCallPart("create_verification_identity", {})
60
+ elif n == 1:
61
+ state["inbox"] = json.loads(last)
62
+ call = ToolCallPart("python", {"code": (
63
+ f"goto_url({DEMO!r}); wait_for_load()\n"
64
+ f"fill_input('#email', {state['inbox']['email']!r})\n"
65
+ "js(\"document.querySelector('button[type=submit]').click()\"); wait(1); wait_for_load()\n"
66
+ "print(js('document.querySelector(\"h1\").textContent'))"
67
+ )})
68
+ elif n == 2:
69
+ assert "Check your inbox" in last, last
70
+ call = ToolCallPart("wait_for_verification_code", {"identity_id": state["inbox"]["identity_id"], "timeout_seconds": 60})
71
+ elif n == 3:
72
+ state["code"] = json.loads(last)["code"]
73
+ call = ToolCallPart("python", {"code": (
74
+ f"fill_input('#code', {state['code']!r})\n"
75
+ "js(\"document.querySelector('button[type=submit]').click()\"); wait(1); wait_for_load()\n"
76
+ "print(js('document.querySelector(\"#otpauth-uri\").textContent'))"
77
+ )})
78
+ elif n == 4:
79
+ uri = re.search(r"otpauth://\S+", last).group(0)
80
+ call = ToolCallPart("enroll_authenticator", {"identity_id": state["inbox"]["identity_id"], "otpauth_uri": uri})
81
+ elif n == 5 or state.get("phase") == "fresh":
82
+ got = json.loads(last)
83
+ if n == 5:
84
+ state["authenticator_id"] = got["authenticator_id"]
85
+ if got.get("seconds_remaining", 30) < 5 and state.get("phase") != "fresh":
86
+ # a code with <5 s left may expire before the form posts: wait out the period, then ask again
87
+ state["phase"] = "waiting"
88
+ call = ToolCallPart("python", {"code": f"wait({got['seconds_remaining'] + 1}); print('period rolled')"})
89
+ else:
90
+ state["phase"] = "submitted"
91
+ call = ToolCallPart("python", {"code": _submit_totp(got["code"])})
92
+ elif state.get("phase") == "waiting":
93
+ state["phase"] = "fresh"
94
+ call = ToolCallPart("get_authenticator_code", {"identity_id": state["inbox"]["identity_id"],
95
+ "authenticator_id": state["authenticator_id"]})
96
+ else:
97
+ call = ToolCallPart("finish", {"result": last.strip()[:500], "success": "all set" in last})
98
+ return ModelResponse(parts=[call])
99
+
100
+ return FunctionModel(step, model_name="scripted-acme")
101
+
102
+
103
+ async def test_agent_signs_up_on_acme_with_humanless_actions():
104
+ # sandbox keys are limited to 5 per hour per IP: reuse one with HUMANLESS_SANDBOX_KEY=hl_live_...
105
+ key = os.environ.get("HUMANLESS_SANDBOX_KEY") or (await create_sandbox_key())["key"]
106
+ humanless = HumanlessActions(key)
107
+ tools = humanless.register(Tools())
108
+ agent = Agent(
109
+ "Create an account on the Acme demo app, verify the email and turn on 2FA.",
110
+ llm=scripted_model(),
111
+ browser=Browser("chromium", headless=True),
112
+ tools=tools,
113
+ judge=False,
114
+ )
115
+ try:
116
+ history = await agent.run(max_steps=15, timeout=240)
117
+ finally:
118
+ await humanless.cleanup()
119
+ result = str(history.final_result())
120
+ assert "all set" in result, result
121
+ assert "two-factor authentication turned on" in result
122
+ assert humanless.created == []