diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 66aa23d9..ac2db402 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,7 +19,7 @@ jobs: runs-on: ${{ github.repository == 'stainless-sdks/stagehand-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} if: github.event_name == 'push' || github.event.pull_request.head.repo.fork steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Install uv uses: astral-sh/setup-uv@v5 @@ -41,7 +41,7 @@ jobs: id-token: write runs-on: ${{ github.repository == 'stainless-sdks/stagehand-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Install uv uses: astral-sh/setup-uv@v5 @@ -57,7 +57,7 @@ jobs: - name: Get GitHub OIDC Token if: github.repository == 'stainless-sdks/stagehand-python' id: github-oidc - uses: actions/github-script@v6 + uses: actions/github-script@v8 with: script: core.setOutput('github_token', await core.getIDToken()); @@ -75,7 +75,7 @@ jobs: runs-on: ${{ github.repository == 'stainless-sdks/stagehand-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} if: github.event_name == 'push' || github.event.pull_request.head.repo.fork steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Install uv uses: astral-sh/setup-uv@v5 diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index d77d01ad..df4a2d0e 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -38,7 +38,7 @@ jobs: contents: read steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Install uv uses: astral-sh/setup-uv@v5 diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index 23563b96..dba7811e 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -2,7 +2,7 @@ name: Release Doctor on: pull_request: branches: - - main + - stainless workflow_dispatch: jobs: @@ -12,7 +12,7 @@ jobs: if: github.repository == 'browserbase/stagehand-python' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Check release environment run: | diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 06c9b658..30f01a3e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "3.4.7" -} \ No newline at end of file + ".": "3.4.8" +} diff --git a/.stats.yml b/.stats.yml index cb872bbf..b1b40bd8 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 7 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/browserbase%2Fstagehand-991d1530002115ecec027f98cad357d39ca1ece6784f62d48e6740b8830e1104.yml -openapi_spec_hash: 303329893ced56b2c129fb9fd666144e -config_hash: 46336540a7b06c89308171858ad8238c +configured_endpoints: 8 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/browserbase%2Fstagehand-089c8670f1d7c2e9fa8e5c97010db7c24b8f162eb7cfe76ffa41d70fa46efe2f.yml +openapi_spec_hash: 7a226aee8f3f2ab16febbe6bb35e1657 +config_hash: 242651c4871c2869ba3c2e3d337505b9 diff --git a/CHANGELOG.md b/CHANGELOG.md index d296e594..76e9490e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 3.4.8 (2026-01-27) + +Full Changelog: [v3.4.7...v3.4.8](https://github.com/browserbase/stagehand-python/compare/v3.4.7...v3.4.8) + +### Chores + +* sync repo ([efaf774](https://github.com/browserbase/stagehand-python/commit/efaf774f0dbd93db8e15e5c3800d62dd7670006c)) + ## 3.4.7 (2026-01-15) Full Changelog: [v3.4.6...v3.4.7](https://github.com/browserbase/stagehand-python/compare/v3.4.6...v3.4.7) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0410f495..5a1ac87e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -91,7 +91,7 @@ If you’d like to use the repository from source, you can either install from g To install via git: ```sh -uv run pip install git+ssh://git@github.com/browserbase/stagehand-python#stainless.git +$ uv run pip install git+ssh://git@github.com/browserbase/stagehand-python.git ``` Alternatively, you can build from source and install the wheel file: diff --git a/LICENSE b/LICENSE index d15d0212..a7b82c2f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,7 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ +Copyright 2026 stagehand - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - 1. Definitions. +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2026 Stagehand - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index e9611936..1a19352a 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,8 @@
+ +[)](https://pypi.org/project/stagehand/)
@@ -69,6 +71,7 @@ Most existing browser automation tools either require you to write low-level cod
## Installation
```sh
+# install from PyPI
uv pip install stagehand
```
@@ -323,7 +326,8 @@ By default, the async client uses `httpx` for HTTP requests. For improved concur
Install `aiohttp`:
```sh
-uv run pip install stagehand[aiohttp]
+# install from PyPI
+uv pip install stagehand[aiohttp]
```
Then instantiate the client with `http_client=DefaultAioHttpClient()`:
@@ -585,7 +589,122 @@ if response.my_field is None:
print('Got json like {"my_field": null}.')
```
-## Semantic versioning
+### Accessing raw response data (e.g. headers)
+
+The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g.,
+
+```py
+from stagehand import Stagehand
+
+client = Stagehand()
+response = client.sessions.with_raw_response.start(
+ model_name="openai/gpt-5-nano",
+)
+print(response.headers.get('X-My-Header'))
+
+session = response.parse() # get the object that `sessions.start()` would have returned
+print(session.data)
+```
+
+These methods return an [`APIResponse`](https://github.com/browserbase/stagehand-python/tree/stainless/src/stagehand/_response.py) object.
+
+The async client returns an [`AsyncAPIResponse`](https://github.com/browserbase/stagehand-python/tree/stainless/src/stagehand/_response.py) with the same structure, the only difference being `await`able methods for reading the response content.
+
+#### `.with_streaming_response`
+
+The above interface eagerly reads the full response body when you make the request, which may not always be what you want.
+
+To stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods.
+
+```python
+with client.sessions.with_streaming_response.start(
+ model_name="openai/gpt-5-nano",
+) as response:
+ print(response.headers.get("X-My-Header"))
+
+ for line in response.iter_lines():
+ print(line)
+```
+
+The context manager is required so that the response will reliably be closed.
+
+### Making custom/undocumented requests
+
+This library is typed for convenient access to the documented API.
+
+If you need to access undocumented endpoints, params, or response properties, the library can still be used.
+
+#### Undocumented endpoints
+
+To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other
+http verbs. Options on the client will be respected (such as retries) when making this request.
+
+```py
+import httpx
+
+response = client.post(
+ "/foo",
+ cast_to=httpx.Response,
+ body={"my_param": True},
+)
+
+print(response.headers.get("x-foo"))
+```
+
+#### Undocumented request params
+
+If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request
+options.
+
+#### Undocumented response properties
+
+To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You
+can also get all the extra fields on the Pydantic model as a dict with
+[`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra).
+
+### Configuring the HTTP client
+
+You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including:
+
+- Support for [proxies](https://www.python-httpx.org/advanced/proxies/)
+- Custom [transports](https://www.python-httpx.org/advanced/transports/)
+- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality
+
+```python
+import httpx
+from stagehand import Stagehand, DefaultHttpxClient
+
+client = Stagehand(
+ # Or use the `STAGEHAND_BASE_URL` env var
+ base_url="http://my.test.server.example.com:8083",
+ http_client=DefaultHttpxClient(
+ proxy="http://my.test.proxy.example.com",
+ transport=httpx.HTTPTransport(local_address="0.0.0.0"),
+ ),
+)
+```
+
+You can also customize the client on a per-request basis by using `with_options()`:
+
+```python
+client.with_options(http_client=DefaultHttpxClient(...))
+```
+
+### Managing HTTP resources
+
+By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting.
+
+```py
+from stagehand import Stagehand
+
+with Stagehand() as client:
+ # make requests here
+ ...
+
+# HTTP client is now closed
+```
+
+## Versioning
This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:
diff --git a/api.md b/api.md
index dae59737..35e54941 100644
--- a/api.md
+++ b/api.md
@@ -13,6 +13,7 @@ from stagehand.types import (
SessionExtractResponse,
SessionNavigateResponse,
SessionObserveResponse,
+ SessionReplayResponse,
SessionStartResponse,
)
```
@@ -20,9 +21,10 @@ from stagehand.types import (
Methods:
-
client.sessions.act(id, \*\*params) -> SessionActResponse
-- client.sessions.end(id, \*\*params) -> SessionEndResponse
+- client.sessions.end(id) -> SessionEndResponse
- client.sessions.execute(id, \*\*params) -> SessionExecuteResponse
- client.sessions.extract(id, \*\*params) -> SessionExtractResponse
- client.sessions.navigate(id, \*\*params) -> SessionNavigateResponse
- client.sessions.observe(id, \*\*params) -> SessionObserveResponse
+- client.sessions.replay(id) -> SessionReplayResponse
- client.sessions.start(\*\*params) -> SessionStartResponse
diff --git a/examples/byob_example.py b/examples/byob_example.py
index 7771c1c2..ea403508 100644
--- a/examples/byob_example.py
+++ b/examples/byob_example.py
@@ -14,7 +14,7 @@
Usage:
```
-pip install playwright stagehand-alpha
+pip install playwright stagehand
# (if Playwright is new) playwright install chromium
uv run python examples/byob_example.py
```
diff --git a/examples/local_example.py b/examples/local_example.py
index 644e0244..38c8919a 100644
--- a/examples/local_example.py
+++ b/examples/local_example.py
@@ -10,7 +10,7 @@
You can also set `OPENAI_API_KEY` if you prefer, but the example defaults to `MODEL_API_KEY`.
Install the published wheel before running this script:
- `pip install stagehand-alpha`
+ `pip install stagehand`
Then execute this example with the same interpreter:
`python examples/local_example.py`
"""
diff --git a/pyproject.toml b/pyproject.toml
index b872e67b..9a453402 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,9 +1,9 @@
[project]
name = "stagehand"
-version = "3.4.7"
+version = "3.4.8"
description = "The official Python library for the stagehand API"
dynamic = ["readme"]
-license = "Apache-2.0"
+license = "MIT"
authors = [
{ name = "Stagehand", email = "" },
]
@@ -33,7 +33,7 @@ classifiers = [
"Operating System :: POSIX :: Linux",
"Operating System :: Microsoft :: Windows",
"Topic :: Software Development :: Libraries :: Python Modules",
- "License :: OSI Approved :: Apache Software License"
+ "License :: OSI Approved :: MIT License"
]
[project.urls]
diff --git a/requirements-dev.lock b/requirements-dev.lock
index 0bb435b6..d6a2ab28 100644
--- a/requirements-dev.lock
+++ b/requirements-dev.lock
@@ -6,7 +6,7 @@ annotated-types==0.7.0
anyio==4.12.0
# via
# httpx
- # stagehand-alpha
+ # stagehand
backports-asyncio-runner==1.2.0 ; python_full_version < '3.11'
# via pytest-asyncio
certifi==2025.11.12
@@ -17,7 +17,8 @@ colorama==0.4.6 ; sys_platform == 'win32'
# via pytest
dirty-equals==0.11
distro==1.9.0
- # via stagehand-alpha
+ # via stagehand
+dotenv==0.9.9
exceptiongroup==1.3.1 ; python_full_version < '3.11'
# via
# anyio
@@ -31,7 +32,7 @@ httpcore==1.0.9
httpx==0.28.1
# via
# respx
- # stagehand-alpha
+ # stagehand
idna==3.11
# via
# anyio
@@ -59,7 +60,7 @@ pathspec==0.12.1
pluggy==1.6.0
# via pytest
pydantic==2.12.5
- # via stagehand-alpha
+ # via stagehand
pydantic-core==2.41.5
# via pydantic
pygments==2.19.2
@@ -80,13 +81,15 @@ pytest-asyncio==1.3.0 ; python_full_version >= '3.10'
pytest-xdist==3.8.0
python-dateutil==2.9.0.post0 ; python_full_version < '3.10'
# via time-machine
+python-dotenv==1.2.1
+ # via dotenv
respx==0.22.0
rich==14.2.0
ruff==0.14.7
six==1.17.0 ; python_full_version < '3.10'
# via python-dateutil
sniffio==1.3.1
- # via stagehand-alpha
+ # via stagehand
time-machine==2.19.0 ; python_full_version < '3.10'
time-machine==3.1.0 ; python_full_version >= '3.10'
tomli==2.3.0 ; python_full_version < '3.11'
@@ -102,7 +105,7 @@ typing-extensions==4.15.0
# pydantic-core
# pyright
# pytest-asyncio
- # stagehand-alpha
+ # stagehand
# typing-inspection
typing-inspection==0.4.2
# via pydantic
diff --git a/src/stagehand/_base_client.py b/src/stagehand/_base_client.py
index a415befe..0f401f90 100644
--- a/src/stagehand/_base_client.py
+++ b/src/stagehand/_base_client.py
@@ -9,6 +9,7 @@
import inspect
import logging
import platform
+import warnings
import email.utils
from types import TracebackType
from random import random
@@ -51,9 +52,11 @@
ResponseT,
AnyMapping,
PostParser,
+ BinaryTypes,
RequestFiles,
HttpxSendArgs,
RequestOptions,
+ AsyncBinaryTypes,
HttpxRequestFiles,
ModelBuilderProtocol,
not_given,
@@ -477,8 +480,19 @@ def _build_request(
retries_taken: int = 0,
) -> httpx.Request:
if log.isEnabledFor(logging.DEBUG):
- log.debug("Request options: %s", model_dump(options, exclude_unset=True))
-
+ log.debug(
+ "Request options: %s",
+ model_dump(
+ options,
+ exclude_unset=True,
+ # Pydantic v1 can't dump every type we support in content, so we exclude it for now.
+ exclude={
+ "content",
+ }
+ if PYDANTIC_V1
+ else {},
+ ),
+ )
kwargs: dict[str, Any] = {}
json_data = options.json_data
@@ -532,7 +546,13 @@ def _build_request(
is_body_allowed = options.method.lower() != "get"
if is_body_allowed:
- if isinstance(json_data, bytes):
+ if options.content is not None and json_data is not None:
+ raise TypeError("Passing both `content` and `json_data` is not supported")
+ if options.content is not None and files is not None:
+ raise TypeError("Passing both `content` and `files` is not supported")
+ if options.content is not None:
+ kwargs["content"] = options.content
+ elif isinstance(json_data, bytes):
kwargs["content"] = json_data
else:
kwargs["json"] = json_data if is_given(json_data) else None
@@ -1194,6 +1214,7 @@ def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
options: RequestOptions = {},
files: RequestFiles | None = None,
stream: Literal[False] = False,
@@ -1206,6 +1227,7 @@ def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
options: RequestOptions = {},
files: RequestFiles | None = None,
stream: Literal[True],
@@ -1219,6 +1241,7 @@ def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
options: RequestOptions = {},
files: RequestFiles | None = None,
stream: bool,
@@ -1231,13 +1254,25 @@ def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
options: RequestOptions = {},
files: RequestFiles | None = None,
stream: bool = False,
stream_cls: type[_StreamT] | None = None,
) -> ResponseT | _StreamT:
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if files is not None and content is not None:
+ raise TypeError("Passing both `files` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
opts = FinalRequestOptions.construct(
- method="post", url=path, json_data=body, files=to_httpx_files(files), **options
+ method="post", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
)
return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
@@ -1247,11 +1282,23 @@ def patch(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
) -> ResponseT:
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if files is not None and content is not None:
+ raise TypeError("Passing both `files` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
opts = FinalRequestOptions.construct(
- method="patch", url=path, json_data=body, files=to_httpx_files(files), **options
+ method="patch", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
)
return self.request(cast_to, opts)
@@ -1261,11 +1308,23 @@ def put(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
) -> ResponseT:
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if files is not None and content is not None:
+ raise TypeError("Passing both `files` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
opts = FinalRequestOptions.construct(
- method="put", url=path, json_data=body, files=to_httpx_files(files), **options
+ method="put", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
)
return self.request(cast_to, opts)
@@ -1275,9 +1334,19 @@ def delete(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
options: RequestOptions = {},
) -> ResponseT:
- opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, **options)
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options)
return self.request(cast_to, opts)
def get_api_list(
@@ -1717,6 +1786,7 @@ async def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
stream: Literal[False] = False,
@@ -1729,6 +1799,7 @@ async def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
stream: Literal[True],
@@ -1742,6 +1813,7 @@ async def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
stream: bool,
@@ -1754,13 +1826,25 @@ async def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
stream: bool = False,
stream_cls: type[_AsyncStreamT] | None = None,
) -> ResponseT | _AsyncStreamT:
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if files is not None and content is not None:
+ raise TypeError("Passing both `files` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
opts = FinalRequestOptions.construct(
- method="post", url=path, json_data=body, files=await async_to_httpx_files(files), **options
+ method="post", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options
)
return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
@@ -1770,11 +1854,28 @@ async def patch(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
) -> ResponseT:
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if files is not None and content is not None:
+ raise TypeError("Passing both `files` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
opts = FinalRequestOptions.construct(
- method="patch", url=path, json_data=body, files=await async_to_httpx_files(files), **options
+ method="patch",
+ url=path,
+ json_data=body,
+ content=content,
+ files=await async_to_httpx_files(files),
+ **options,
)
return await self.request(cast_to, opts)
@@ -1784,11 +1885,23 @@ async def put(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
) -> ResponseT:
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if files is not None and content is not None:
+ raise TypeError("Passing both `files` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
opts = FinalRequestOptions.construct(
- method="put", url=path, json_data=body, files=await async_to_httpx_files(files), **options
+ method="put", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options
)
return await self.request(cast_to, opts)
@@ -1798,9 +1911,19 @@ async def delete(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
options: RequestOptions = {},
) -> ResponseT:
- opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, **options)
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options)
return await self.request(cast_to, opts)
def get_api_list(
diff --git a/src/stagehand/_models.py b/src/stagehand/_models.py
index ca9500b2..29070e05 100644
--- a/src/stagehand/_models.py
+++ b/src/stagehand/_models.py
@@ -3,7 +3,20 @@
import os
import inspect
import weakref
-from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, Optional, cast
+from typing import (
+ IO,
+ TYPE_CHECKING,
+ Any,
+ Type,
+ Union,
+ Generic,
+ TypeVar,
+ Callable,
+ Iterable,
+ Optional,
+ AsyncIterable,
+ cast,
+)
from datetime import date, datetime
from typing_extensions import (
List,
@@ -787,6 +800,7 @@ class FinalRequestOptionsInput(TypedDict, total=False):
timeout: float | Timeout | None
files: HttpxRequestFiles | None
idempotency_key: str
+ content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None]
json_data: Body
extra_json: AnyMapping
follow_redirects: bool
@@ -805,6 +819,7 @@ class FinalRequestOptions(pydantic.BaseModel):
post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven()
follow_redirects: Union[bool, None] = None
+ content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None] = None
# It should be noted that we cannot use `json` here as that would override
# a BaseModel method in an incompatible fashion.
json_data: Union[Body, None] = None
diff --git a/src/stagehand/_types.py b/src/stagehand/_types.py
index c2ce0d7a..d25d0560 100644
--- a/src/stagehand/_types.py
+++ b/src/stagehand/_types.py
@@ -13,9 +13,11 @@
Mapping,
TypeVar,
Callable,
+ Iterable,
Iterator,
Optional,
Sequence,
+ AsyncIterable,
)
from typing_extensions import (
Set,
@@ -56,6 +58,13 @@
else:
Base64FileInput = Union[IO[bytes], PathLike]
FileContent = Union[IO[bytes], bytes, PathLike] # PathLike is not subscriptable in Python 3.8.
+
+
+# Used for sending raw binary data / streaming data in request bodies
+# e.g. for file uploads without multipart encoding
+BinaryTypes = Union[bytes, bytearray, IO[bytes], Iterable[bytes]]
+AsyncBinaryTypes = Union[bytes, bytearray, IO[bytes], AsyncIterable[bytes]]
+
FileTypes = Union[
# file (or bytes)
FileContent,
diff --git a/src/stagehand/_version.py b/src/stagehand/_version.py
index ba209e07..eeba836f 100644
--- a/src/stagehand/_version.py
+++ b/src/stagehand/_version.py
@@ -1,4 +1,4 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
__title__ = "stagehand"
-__version__ = "3.4.7" # x-release-please-version
+__version__ = "3.4.8" # x-release-please-version
diff --git a/src/stagehand/resources/sessions.py b/src/stagehand/resources/sessions.py
index 68bee54c..09ed74c3 100644
--- a/src/stagehand/resources/sessions.py
+++ b/src/stagehand/resources/sessions.py
@@ -2,8 +2,7 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Dict, Union
-from datetime import datetime, timezone
+from typing import Dict, Optional
from typing_extensions import Literal, overload
import httpx
@@ -16,9 +15,6 @@
session_observe_params,
session_navigate_params,
)
-
-if TYPE_CHECKING:
- from .._client import Stagehand, AsyncStagehand
from .._types import Body, Omit, Query, Headers, NotGiven, omit, not_given
from .._utils import is_given, required_args, maybe_transform, strip_not_given, async_maybe_transform
from .._compat import cached_property
@@ -30,12 +26,12 @@
async_to_streamed_response_wrapper,
)
from .._streaming import Stream, AsyncStream
-from .._exceptions import StagehandError
from .._base_client import make_request_options
from ..types.stream_event import StreamEvent
from ..types.session_act_response import SessionActResponse
from ..types.session_end_response import SessionEndResponse
from ..types.session_start_response import SessionStartResponse
+from ..types.session_replay_response import SessionReplayResponse
from ..types.session_execute_response import SessionExecuteResponse
from ..types.session_extract_response import SessionExtractResponse
from ..types.session_observe_response import SessionObserveResponse
@@ -44,29 +40,6 @@
__all__ = ["SessionsResource", "AsyncSessionsResource"]
-def _format_x_sent_at(value: Union[str, datetime] | Omit) -> str | NotGiven:
- if isinstance(value, datetime):
- if value.tzinfo is None:
- value = value.replace(tzinfo=timezone.utc)
- value = value.astimezone(timezone.utc)
- return value.isoformat().replace("+00:00", "Z")
- if isinstance(value, Omit):
- return not_given
- return value
-
-
-def _requires_browserbase_credentials(
- _: "Stagehand | AsyncStagehand",
- browser: session_start_params.Browser | Omit,
-) -> bool:
- if not is_given(browser):
- return True
-
- browser_type = browser.get("type")
-
- return browser_type != "local"
-
-
class SessionsResource(SyncAPIResource):
@cached_property
def with_raw_response(self) -> SessionsResourceWithRawResponse:
@@ -93,10 +66,9 @@ def act(
id: str,
*,
input: session_act_params.Input,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
options: session_act_params.Options | Omit = omit,
stream_response: Literal[False] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -118,8 +90,6 @@ def act(
stream_response: Whether to stream the response via SSE
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -139,9 +109,8 @@ def act(
*,
input: session_act_params.Input,
stream_response: Literal[True],
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
options: session_act_params.Options | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -163,8 +132,6 @@ def act(
frame_id: Target frame ID for the action
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -184,9 +151,8 @@ def act(
*,
input: session_act_params.Input,
stream_response: bool,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
options: session_act_params.Options | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -208,8 +174,6 @@ def act(
frame_id: Target frame ID for the action
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -228,10 +192,9 @@ def act(
id: str,
*,
input: session_act_params.Input,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
options: session_act_params.Options | Omit = omit,
stream_response: Literal[False] | Literal[True] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -244,10 +207,7 @@ def act(
raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
@@ -276,8 +236,6 @@ def end(
self,
id: str,
*,
- _force_body: object | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -292,8 +250,6 @@ def end(
Args:
id: Unique session identifier
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -308,16 +264,12 @@ def end(
raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
return self._post(
f"/v1/sessions/{id}/end",
- body={}, # Empty object to satisfy Content-Type requirement
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -331,9 +283,9 @@ def execute(
*,
agent_config: session_execute_params.AgentConfig,
execute_options: session_execute_params.ExecuteOptions,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
+ should_cache: bool | Omit = omit,
stream_response: Literal[False] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -350,9 +302,9 @@ def execute(
frame_id: Target frame ID for the agent
- stream_response: Whether to stream the response via SSE
+ should_cache: If true, the server captures a cache entry and returns it to the client
- x_sent_at: ISO timestamp when request was sent
+ stream_response: Whether to stream the response via SSE
x_stream_response: Whether to stream the response via SSE
@@ -374,8 +326,8 @@ def execute(
agent_config: session_execute_params.AgentConfig,
execute_options: session_execute_params.ExecuteOptions,
stream_response: Literal[True],
- frame_id: str | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
+ should_cache: bool | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -394,7 +346,7 @@ def execute(
frame_id: Target frame ID for the agent
- x_sent_at: ISO timestamp when request was sent
+ should_cache: If true, the server captures a cache entry and returns it to the client
x_stream_response: Whether to stream the response via SSE
@@ -416,8 +368,8 @@ def execute(
agent_config: session_execute_params.AgentConfig,
execute_options: session_execute_params.ExecuteOptions,
stream_response: bool,
- frame_id: str | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
+ should_cache: bool | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -436,7 +388,7 @@ def execute(
frame_id: Target frame ID for the agent
- x_sent_at: ISO timestamp when request was sent
+ should_cache: If true, the server captures a cache entry and returns it to the client
x_stream_response: Whether to stream the response via SSE
@@ -457,9 +409,9 @@ def execute(
*,
agent_config: session_execute_params.AgentConfig,
execute_options: session_execute_params.ExecuteOptions,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
+ should_cache: bool | Omit = omit,
stream_response: Literal[False] | Literal[True] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -472,10 +424,7 @@ def execute(
raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
@@ -486,6 +435,7 @@ def execute(
"agent_config": agent_config,
"execute_options": execute_options,
"frame_id": frame_id,
+ "should_cache": should_cache,
"stream_response": stream_response,
},
session_execute_params.SessionExecuteParamsStreaming
@@ -505,12 +455,11 @@ def extract(
self,
id: str,
*,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_extract_params.Options | Omit = omit,
schema: Dict[str, object] | Omit = omit,
stream_response: Literal[False] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -533,8 +482,6 @@ def extract(
stream_response: Whether to stream the response via SSE
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -553,11 +500,10 @@ def extract(
id: str,
*,
stream_response: Literal[True],
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_extract_params.Options | Omit = omit,
schema: Dict[str, object] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -580,8 +526,6 @@ def extract(
schema: JSON Schema defining the structure of data to extract
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -600,11 +544,10 @@ def extract(
id: str,
*,
stream_response: bool,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_extract_params.Options | Omit = omit,
schema: Dict[str, object] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -627,8 +570,6 @@ def extract(
schema: JSON Schema defining the structure of data to extract
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -645,12 +586,11 @@ def extract(
self,
id: str,
*,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_extract_params.Options | Omit = omit,
schema: Dict[str, object] | Omit = omit,
stream_response: Literal[False] | Literal[True] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -663,10 +603,7 @@ def extract(
raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
@@ -697,10 +634,9 @@ def navigate(
id: str,
*,
url: str,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
options: session_navigate_params.Options | Omit = omit,
stream_response: bool | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -721,8 +657,6 @@ def navigate(
stream_response: Whether to stream the response via SSE
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -737,10 +671,7 @@ def navigate(
raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
@@ -766,11 +697,10 @@ def observe(
self,
id: str,
*,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_observe_params.Options | Omit = omit,
stream_response: Literal[False] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -792,8 +722,6 @@ def observe(
stream_response: Whether to stream the response via SSE
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -812,10 +740,9 @@ def observe(
id: str,
*,
stream_response: Literal[True],
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_observe_params.Options | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -837,8 +764,6 @@ def observe(
instruction: Natural language instruction for what actions to find
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -857,10 +782,9 @@ def observe(
id: str,
*,
stream_response: bool,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_observe_params.Options | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -882,8 +806,6 @@ def observe(
instruction: Natural language instruction for what actions to find
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -900,11 +822,10 @@ def observe(
self,
id: str,
*,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_observe_params.Options | Omit = omit,
stream_response: Literal[False] | Literal[True] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -917,10 +838,7 @@ def observe(
raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
@@ -945,6 +863,50 @@ def observe(
stream_cls=Stream[StreamEvent],
)
+ def replay(
+ self,
+ id: str,
+ *,
+ x_stream_response: Literal["true", "false"] | Omit = omit,
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
+ # The extra values given here take precedence over values defined on the client or passed to this method.
+ extra_headers: Headers | None = None,
+ extra_query: Query | None = None,
+ extra_body: Body | None = None,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> SessionReplayResponse:
+ """
+ Retrieves replay metrics for a session.
+
+ Args:
+ id: Unique session identifier
+
+ x_stream_response: Whether to stream the response via SSE
+
+ extra_headers: Send extra headers
+
+ extra_query: Add additional query parameters to the request
+
+ extra_body: Add additional JSON properties to the request
+
+ timeout: Override the client-level default timeout for this request, in seconds
+ """
+ if not id:
+ raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
+ extra_headers = {
+ **strip_not_given(
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
+ ),
+ **(extra_headers or {}),
+ }
+ return self._get(
+ f"/v1/sessions/{id}/replay",
+ options=make_request_options(
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
+ ),
+ cast_to=SessionReplayResponse,
+ )
+
def start(
self,
*,
@@ -959,7 +921,6 @@ def start(
system_prompt: str | Omit = omit,
verbose: Literal[0, 1, 2] | Omit = omit,
wait_for_captcha_solves: bool | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -990,8 +951,6 @@ def start(
wait_for_captcha_solves: Wait for captcha solves (deprecated, v2 only)
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1002,22 +961,9 @@ def start(
timeout: Override the client-level default timeout for this request, in seconds
"""
- if _requires_browserbase_credentials(self._client, browser):
- missing: list[str] = []
- if not self._client.browserbase_api_key:
- missing.append("browserbase_api_key")
- if not self._client.browserbase_project_id:
- missing.append("browserbase_project_id")
- if missing:
- raise StagehandError(
- f"Browserbase credentials are required when launching a Browserbase browser: missing {', '.join(missing)}."
- )
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
@@ -1072,10 +1018,9 @@ async def act(
id: str,
*,
input: session_act_params.Input,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
options: session_act_params.Options | Omit = omit,
stream_response: Literal[False] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1097,8 +1042,6 @@ async def act(
stream_response: Whether to stream the response via SSE
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1118,9 +1061,8 @@ async def act(
*,
input: session_act_params.Input,
stream_response: Literal[True],
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
options: session_act_params.Options | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1142,8 +1084,6 @@ async def act(
frame_id: Target frame ID for the action
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1163,9 +1103,8 @@ async def act(
*,
input: session_act_params.Input,
stream_response: bool,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
options: session_act_params.Options | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1187,8 +1126,6 @@ async def act(
frame_id: Target frame ID for the action
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1207,10 +1144,9 @@ async def act(
id: str,
*,
input: session_act_params.Input,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
options: session_act_params.Options | Omit = omit,
stream_response: Literal[False] | Literal[True] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1223,10 +1159,7 @@ async def act(
raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
@@ -1255,8 +1188,6 @@ async def end(
self,
id: str,
*,
- _force_body: object | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1271,8 +1202,6 @@ async def end(
Args:
id: Unique session identifier
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1287,16 +1216,12 @@ async def end(
raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
return await self._post(
f"/v1/sessions/{id}/end",
- body={}, # Empty object to satisfy Content-Type requirement
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -1310,9 +1235,9 @@ async def execute(
*,
agent_config: session_execute_params.AgentConfig,
execute_options: session_execute_params.ExecuteOptions,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
+ should_cache: bool | Omit = omit,
stream_response: Literal[False] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1329,9 +1254,9 @@ async def execute(
frame_id: Target frame ID for the agent
- stream_response: Whether to stream the response via SSE
+ should_cache: If true, the server captures a cache entry and returns it to the client
- x_sent_at: ISO timestamp when request was sent
+ stream_response: Whether to stream the response via SSE
x_stream_response: Whether to stream the response via SSE
@@ -1353,8 +1278,8 @@ async def execute(
agent_config: session_execute_params.AgentConfig,
execute_options: session_execute_params.ExecuteOptions,
stream_response: Literal[True],
- frame_id: str | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
+ should_cache: bool | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1373,7 +1298,7 @@ async def execute(
frame_id: Target frame ID for the agent
- x_sent_at: ISO timestamp when request was sent
+ should_cache: If true, the server captures a cache entry and returns it to the client
x_stream_response: Whether to stream the response via SSE
@@ -1395,8 +1320,8 @@ async def execute(
agent_config: session_execute_params.AgentConfig,
execute_options: session_execute_params.ExecuteOptions,
stream_response: bool,
- frame_id: str | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
+ should_cache: bool | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1415,7 +1340,7 @@ async def execute(
frame_id: Target frame ID for the agent
- x_sent_at: ISO timestamp when request was sent
+ should_cache: If true, the server captures a cache entry and returns it to the client
x_stream_response: Whether to stream the response via SSE
@@ -1436,9 +1361,9 @@ async def execute(
*,
agent_config: session_execute_params.AgentConfig,
execute_options: session_execute_params.ExecuteOptions,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
+ should_cache: bool | Omit = omit,
stream_response: Literal[False] | Literal[True] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1451,10 +1376,7 @@ async def execute(
raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
@@ -1465,6 +1387,7 @@ async def execute(
"agent_config": agent_config,
"execute_options": execute_options,
"frame_id": frame_id,
+ "should_cache": should_cache,
"stream_response": stream_response,
},
session_execute_params.SessionExecuteParamsStreaming
@@ -1484,12 +1407,11 @@ async def extract(
self,
id: str,
*,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_extract_params.Options | Omit = omit,
schema: Dict[str, object] | Omit = omit,
stream_response: Literal[False] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1512,8 +1434,6 @@ async def extract(
stream_response: Whether to stream the response via SSE
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1532,11 +1452,10 @@ async def extract(
id: str,
*,
stream_response: Literal[True],
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_extract_params.Options | Omit = omit,
schema: Dict[str, object] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1559,8 +1478,6 @@ async def extract(
schema: JSON Schema defining the structure of data to extract
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1579,11 +1496,10 @@ async def extract(
id: str,
*,
stream_response: bool,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_extract_params.Options | Omit = omit,
schema: Dict[str, object] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1606,8 +1522,6 @@ async def extract(
schema: JSON Schema defining the structure of data to extract
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1624,12 +1538,11 @@ async def extract(
self,
id: str,
*,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_extract_params.Options | Omit = omit,
schema: Dict[str, object] | Omit = omit,
stream_response: Literal[False] | Literal[True] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1642,10 +1555,7 @@ async def extract(
raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
@@ -1676,10 +1586,9 @@ async def navigate(
id: str,
*,
url: str,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
options: session_navigate_params.Options | Omit = omit,
stream_response: bool | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1700,8 +1609,6 @@ async def navigate(
stream_response: Whether to stream the response via SSE
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1716,10 +1623,7 @@ async def navigate(
raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
@@ -1745,11 +1649,10 @@ async def observe(
self,
id: str,
*,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_observe_params.Options | Omit = omit,
stream_response: Literal[False] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1771,8 +1674,6 @@ async def observe(
stream_response: Whether to stream the response via SSE
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1791,10 +1692,9 @@ async def observe(
id: str,
*,
stream_response: Literal[True],
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_observe_params.Options | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1816,8 +1716,6 @@ async def observe(
instruction: Natural language instruction for what actions to find
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1836,10 +1734,9 @@ async def observe(
id: str,
*,
stream_response: bool,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_observe_params.Options | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1861,8 +1758,6 @@ async def observe(
instruction: Natural language instruction for what actions to find
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1879,11 +1774,10 @@ async def observe(
self,
id: str,
*,
- frame_id: str | Omit = omit,
+ frame_id: Optional[str] | Omit = omit,
instruction: str | Omit = omit,
options: session_observe_params.Options | Omit = omit,
stream_response: Literal[False] | Literal[True] | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1896,10 +1790,7 @@ async def observe(
raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
@@ -1924,6 +1815,50 @@ async def observe(
stream_cls=AsyncStream[StreamEvent],
)
+ async def replay(
+ self,
+ id: str,
+ *,
+ x_stream_response: Literal["true", "false"] | Omit = omit,
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
+ # The extra values given here take precedence over values defined on the client or passed to this method.
+ extra_headers: Headers | None = None,
+ extra_query: Query | None = None,
+ extra_body: Body | None = None,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> SessionReplayResponse:
+ """
+ Retrieves replay metrics for a session.
+
+ Args:
+ id: Unique session identifier
+
+ x_stream_response: Whether to stream the response via SSE
+
+ extra_headers: Send extra headers
+
+ extra_query: Add additional query parameters to the request
+
+ extra_body: Add additional JSON properties to the request
+
+ timeout: Override the client-level default timeout for this request, in seconds
+ """
+ if not id:
+ raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
+ extra_headers = {
+ **strip_not_given(
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
+ ),
+ **(extra_headers or {}),
+ }
+ return await self._get(
+ f"/v1/sessions/{id}/replay",
+ options=make_request_options(
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
+ ),
+ cast_to=SessionReplayResponse,
+ )
+
async def start(
self,
*,
@@ -1938,7 +1873,6 @@ async def start(
system_prompt: str | Omit = omit,
verbose: Literal[0, 1, 2] | Omit = omit,
wait_for_captcha_solves: bool | Omit = omit,
- x_sent_at: Union[str, datetime] | Omit = omit,
x_stream_response: Literal["true", "false"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
@@ -1969,8 +1903,6 @@ async def start(
wait_for_captcha_solves: Wait for captcha solves (deprecated, v2 only)
- x_sent_at: ISO timestamp when request was sent
-
x_stream_response: Whether to stream the response via SSE
extra_headers: Send extra headers
@@ -1981,22 +1913,9 @@ async def start(
timeout: Override the client-level default timeout for this request, in seconds
"""
- if _requires_browserbase_credentials(self._client, browser):
- missing: list[str] = []
- if not self._client.browserbase_api_key:
- missing.append("browserbase_api_key")
- if not self._client.browserbase_project_id:
- missing.append("browserbase_project_id")
- if missing:
- raise StagehandError(
- f"Browserbase credentials are required when launching a Browserbase browser: missing {', '.join(missing)}."
- )
extra_headers = {
**strip_not_given(
- {
- "x-sent-at": _format_x_sent_at(x_sent_at),
- "x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given,
- }
+ {"x-stream-response": str(x_stream_response) if is_given(x_stream_response) else not_given}
),
**(extra_headers or {}),
}
@@ -2047,6 +1966,9 @@ def __init__(self, sessions: SessionsResource) -> None:
self.observe = to_raw_response_wrapper(
sessions.observe,
)
+ self.replay = to_raw_response_wrapper(
+ sessions.replay,
+ )
self.start = to_raw_response_wrapper(
sessions.start,
)
@@ -2074,6 +1996,9 @@ def __init__(self, sessions: AsyncSessionsResource) -> None:
self.observe = async_to_raw_response_wrapper(
sessions.observe,
)
+ self.replay = async_to_raw_response_wrapper(
+ sessions.replay,
+ )
self.start = async_to_raw_response_wrapper(
sessions.start,
)
@@ -2101,6 +2026,9 @@ def __init__(self, sessions: SessionsResource) -> None:
self.observe = to_streamed_response_wrapper(
sessions.observe,
)
+ self.replay = to_streamed_response_wrapper(
+ sessions.replay,
+ )
self.start = to_streamed_response_wrapper(
sessions.start,
)
@@ -2128,6 +2056,9 @@ def __init__(self, sessions: AsyncSessionsResource) -> None:
self.observe = async_to_streamed_response_wrapper(
sessions.observe,
)
+ self.replay = async_to_streamed_response_wrapper(
+ sessions.replay,
+ )
self.start = async_to_streamed_response_wrapper(
sessions.start,
)
diff --git a/src/stagehand/types/__init__.py b/src/stagehand/types/__init__.py
index 145b9be0..f7278aa6 100644
--- a/src/stagehand/types/__init__.py
+++ b/src/stagehand/types/__init__.py
@@ -6,7 +6,6 @@
from .stream_event import StreamEvent as StreamEvent
from .model_config_param import ModelConfigParam as ModelConfigParam
from .session_act_params import SessionActParams as SessionActParams
-from .session_end_params import SessionEndParams as SessionEndParams
from .session_act_response import SessionActResponse as SessionActResponse
from .session_end_response import SessionEndResponse as SessionEndResponse
from .session_start_params import SessionStartParams as SessionStartParams
@@ -15,6 +14,7 @@
from .session_observe_params import SessionObserveParams as SessionObserveParams
from .session_start_response import SessionStartResponse as SessionStartResponse
from .session_navigate_params import SessionNavigateParams as SessionNavigateParams
+from .session_replay_response import SessionReplayResponse as SessionReplayResponse
from .session_execute_response import SessionExecuteResponse as SessionExecuteResponse
from .session_extract_response import SessionExtractResponse as SessionExtractResponse
from .session_observe_response import SessionObserveResponse as SessionObserveResponse
diff --git a/src/stagehand/types/model_config_param.py b/src/stagehand/types/model_config_param.py
index f633db12..4699e677 100644
--- a/src/stagehand/types/model_config_param.py
+++ b/src/stagehand/types/model_config_param.py
@@ -2,17 +2,16 @@
from __future__ import annotations
-from typing import Union
-from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict
+from typing_extensions import Literal, Required, Annotated, TypedDict
from .._utils import PropertyInfo
-__all__ = ["ModelConfigParam", "ModelConfigObject"]
+__all__ = ["ModelConfigParam"]
-class ModelConfigObject(TypedDict, total=False):
+class ModelConfigParam(TypedDict, total=False):
model_name: Required[Annotated[str, PropertyInfo(alias="modelName")]]
- """Model name string (e.g., 'openai/gpt-5-nano', 'anthropic/claude-4.5-opus')"""
+ """Model name string with provider prefix (e.g., 'openai/gpt-5-nano')"""
api_key: Annotated[str, PropertyInfo(alias="apiKey")]
"""API key for the model provider"""
@@ -22,6 +21,3 @@ class ModelConfigObject(TypedDict, total=False):
provider: Literal["openai", "anthropic", "google", "microsoft"]
"""AI provider for the model (or provide a baseURL endpoint instead)"""
-
-
-ModelConfigParam: TypeAlias = Union[str, ModelConfigObject]
diff --git a/src/stagehand/types/session_act_params.py b/src/stagehand/types/session_act_params.py
index 605019b8..73c0bf39 100644
--- a/src/stagehand/types/session_act_params.py
+++ b/src/stagehand/types/session_act_params.py
@@ -2,42 +2,44 @@
from __future__ import annotations
-from typing import Dict, Union
-from datetime import datetime
+from typing import Dict, Union, Optional
from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict
from .._utils import PropertyInfo
from .action_param import ActionParam
from .model_config_param import ModelConfigParam
-__all__ = ["SessionActParamsBase", "Input", "Options", "SessionActParamsNonStreaming", "SessionActParamsStreaming"]
+__all__ = [
+ "SessionActParamsBase",
+ "Input",
+ "Options",
+ "OptionsModel",
+ "SessionActParamsNonStreaming",
+ "SessionActParamsStreaming",
+]
class SessionActParamsBase(TypedDict, total=False):
input: Required[Input]
"""Natural language instruction or Action object"""
- frame_id: Annotated[str, PropertyInfo(alias="frameId")]
+ frame_id: Annotated[Optional[str], PropertyInfo(alias="frameId")]
"""Target frame ID for the action"""
options: Options
- x_sent_at: Annotated[Union[str, datetime], PropertyInfo(alias="x-sent-at", format="iso8601")]
- """ISO timestamp when request was sent"""
-
x_stream_response: Annotated[Literal["true", "false"], PropertyInfo(alias="x-stream-response")]
"""Whether to stream the response via SSE"""
Input: TypeAlias = Union[str, ActionParam]
+OptionsModel: TypeAlias = Union[ModelConfigParam, str]
+
class Options(TypedDict, total=False):
- model: ModelConfigParam
- """
- Model name string with provider prefix (e.g., 'openai/gpt-5-nano',
- 'anthropic/claude-4.5-opus')
- """
+ model: OptionsModel
+ """Model configuration object or model name string (e.g., 'openai/gpt-5-nano')"""
timeout: float
"""Timeout in ms for the action"""
diff --git a/src/stagehand/types/session_end_params.py b/src/stagehand/types/session_end_params.py
deleted file mode 100644
index 1998cd27..00000000
--- a/src/stagehand/types/session_end_params.py
+++ /dev/null
@@ -1,21 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from __future__ import annotations
-
-from typing import Union
-from datetime import datetime
-from typing_extensions import Literal, Annotated, TypedDict
-
-from .._utils import PropertyInfo
-
-__all__ = ["SessionEndParams"]
-
-
-class SessionEndParams(TypedDict, total=False):
- _force_body: Annotated[object, PropertyInfo(alias="_forceBody")]
-
- x_sent_at: Annotated[Union[str, datetime], PropertyInfo(alias="x-sent-at", format="iso8601")]
- """ISO timestamp when request was sent"""
-
- x_stream_response: Annotated[Literal["true", "false"], PropertyInfo(alias="x-stream-response")]
- """Whether to stream the response via SSE"""
diff --git a/src/stagehand/types/session_execute_params.py b/src/stagehand/types/session_execute_params.py
index eb8678ff..81d3b4a4 100644
--- a/src/stagehand/types/session_execute_params.py
+++ b/src/stagehand/types/session_execute_params.py
@@ -2,8 +2,7 @@
from __future__ import annotations
-from typing import Union
-from datetime import datetime
+from typing import Union, Optional
from typing_extensions import Literal, Required, Annotated, TypedDict
from .._utils import PropertyInfo
@@ -23,11 +22,11 @@ class SessionExecuteParamsBase(TypedDict, total=False):
execute_options: Required[Annotated[ExecuteOptions, PropertyInfo(alias="executeOptions")]]
- frame_id: Annotated[str, PropertyInfo(alias="frameId")]
+ frame_id: Annotated[Optional[str], PropertyInfo(alias="frameId")]
"""Target frame ID for the agent"""
- x_sent_at: Annotated[Union[str, datetime], PropertyInfo(alias="x-sent-at", format="iso8601")]
- """ISO timestamp when request was sent"""
+ should_cache: Annotated[bool, PropertyInfo(alias="shouldCache")]
+ """If true, the server captures a cache entry and returns it to the client"""
x_stream_response: Annotated[Literal["true", "false"], PropertyInfo(alias="x-stream-response")]
"""Whether to stream the response via SSE"""
diff --git a/src/stagehand/types/session_execute_response.py b/src/stagehand/types/session_execute_response.py
index 7dd4a4b0..71ac670c 100644
--- a/src/stagehand/types/session_execute_response.py
+++ b/src/stagehand/types/session_execute_response.py
@@ -6,7 +6,7 @@
from .._models import BaseModel
-__all__ = ["SessionExecuteResponse", "Data", "DataResult", "DataResultAction", "DataResultUsage"]
+__all__ = ["SessionExecuteResponse", "Data", "DataResult", "DataResultAction", "DataResultUsage", "DataCacheEntry"]
class DataResultAction(BaseModel):
@@ -71,9 +71,19 @@ class DataResult(BaseModel):
usage: Optional[DataResultUsage] = None
+class DataCacheEntry(BaseModel):
+ cache_key: str = FieldInfo(alias="cacheKey")
+ """Opaque cache identifier computed from instruction, URL, options, and config"""
+
+ entry: object
+ """Serialized cache entry that can be written to disk"""
+
+
class Data(BaseModel):
result: DataResult
+ cache_entry: Optional[DataCacheEntry] = FieldInfo(alias="cacheEntry", default=None)
+
class SessionExecuteResponse(BaseModel):
data: Data
diff --git a/src/stagehand/types/session_extract_params.py b/src/stagehand/types/session_extract_params.py
index c763cbb5..5d790192 100644
--- a/src/stagehand/types/session_extract_params.py
+++ b/src/stagehand/types/session_extract_params.py
@@ -2,8 +2,7 @@
from __future__ import annotations
-from typing import Dict, Union
-from datetime import datetime
+from typing import Dict, Union, Optional
from typing_extensions import Literal, Required, Annotated, TypedDict
from .._utils import PropertyInfo
@@ -13,7 +12,7 @@
class SessionExtractParamsBase(TypedDict, total=False):
- frame_id: Annotated[str, PropertyInfo(alias="frameId")]
+ frame_id: Annotated[Optional[str], PropertyInfo(alias="frameId")]
"""Target frame ID for the extraction"""
instruction: str
@@ -24,9 +23,6 @@ class SessionExtractParamsBase(TypedDict, total=False):
schema: Dict[str, object]
"""JSON Schema defining the structure of data to extract"""
- x_sent_at: Annotated[Union[str, datetime], PropertyInfo(alias="x-sent-at", format="iso8601")]
- """ISO timestamp when request was sent"""
-
x_stream_response: Annotated[Literal["true", "false"], PropertyInfo(alias="x-stream-response")]
"""Whether to stream the response via SSE"""
diff --git a/src/stagehand/types/session_navigate_params.py b/src/stagehand/types/session_navigate_params.py
index 39bb2b2e..e93d0ec4 100644
--- a/src/stagehand/types/session_navigate_params.py
+++ b/src/stagehand/types/session_navigate_params.py
@@ -2,8 +2,7 @@
from __future__ import annotations
-from typing import Union
-from datetime import datetime
+from typing import Optional
from typing_extensions import Literal, Required, Annotated, TypedDict
from .._utils import PropertyInfo
@@ -15,7 +14,7 @@ class SessionNavigateParams(TypedDict, total=False):
url: Required[str]
"""URL to navigate to"""
- frame_id: Annotated[str, PropertyInfo(alias="frameId")]
+ frame_id: Annotated[Optional[str], PropertyInfo(alias="frameId")]
"""Target frame ID for the navigation"""
options: Options
@@ -23,9 +22,6 @@ class SessionNavigateParams(TypedDict, total=False):
stream_response: Annotated[bool, PropertyInfo(alias="streamResponse")]
"""Whether to stream the response via SSE"""
- x_sent_at: Annotated[Union[str, datetime], PropertyInfo(alias="x-sent-at", format="iso8601")]
- """ISO timestamp when request was sent"""
-
x_stream_response: Annotated[Literal["true", "false"], PropertyInfo(alias="x-stream-response")]
"""Whether to stream the response via SSE"""
diff --git a/src/stagehand/types/session_observe_params.py b/src/stagehand/types/session_observe_params.py
index 7cad4c85..cce2c391 100644
--- a/src/stagehand/types/session_observe_params.py
+++ b/src/stagehand/types/session_observe_params.py
@@ -2,8 +2,7 @@
from __future__ import annotations
-from typing import Union
-from datetime import datetime
+from typing import Union, Optional
from typing_extensions import Literal, Required, Annotated, TypedDict
from .._utils import PropertyInfo
@@ -13,7 +12,7 @@
class SessionObserveParamsBase(TypedDict, total=False):
- frame_id: Annotated[str, PropertyInfo(alias="frameId")]
+ frame_id: Annotated[Optional[str], PropertyInfo(alias="frameId")]
"""Target frame ID for the observation"""
instruction: str
@@ -21,9 +20,6 @@ class SessionObserveParamsBase(TypedDict, total=False):
options: Options
- x_sent_at: Annotated[Union[str, datetime], PropertyInfo(alias="x-sent-at", format="iso8601")]
- """ISO timestamp when request was sent"""
-
x_stream_response: Annotated[Literal["true", "false"], PropertyInfo(alias="x-stream-response")]
"""Whether to stream the response via SSE"""
diff --git a/src/stagehand/types/session_replay_response.py b/src/stagehand/types/session_replay_response.py
new file mode 100644
index 00000000..a8a81fde
--- /dev/null
+++ b/src/stagehand/types/session_replay_response.py
@@ -0,0 +1,42 @@
+# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+
+from typing import List, Optional
+
+from pydantic import Field as FieldInfo
+
+from .._models import BaseModel
+
+__all__ = ["SessionReplayResponse", "Data", "DataPage", "DataPageAction", "DataPageActionTokenUsage"]
+
+
+class DataPageActionTokenUsage(BaseModel):
+ cached_input_tokens: Optional[float] = FieldInfo(alias="cachedInputTokens", default=None)
+
+ input_tokens: Optional[float] = FieldInfo(alias="inputTokens", default=None)
+
+ output_tokens: Optional[float] = FieldInfo(alias="outputTokens", default=None)
+
+ reasoning_tokens: Optional[float] = FieldInfo(alias="reasoningTokens", default=None)
+
+ time_ms: Optional[float] = FieldInfo(alias="timeMs", default=None)
+
+
+class DataPageAction(BaseModel):
+ method: Optional[str] = None
+
+ token_usage: Optional[DataPageActionTokenUsage] = FieldInfo(alias="tokenUsage", default=None)
+
+
+class DataPage(BaseModel):
+ actions: Optional[List[DataPageAction]] = None
+
+
+class Data(BaseModel):
+ pages: Optional[List[DataPage]] = None
+
+
+class SessionReplayResponse(BaseModel):
+ data: Data
+
+ success: bool
+ """Indicates whether the request was successful"""
diff --git a/src/stagehand/types/session_start_params.py b/src/stagehand/types/session_start_params.py
index 03735673..2df12abd 100644
--- a/src/stagehand/types/session_start_params.py
+++ b/src/stagehand/types/session_start_params.py
@@ -3,7 +3,6 @@
from __future__ import annotations
from typing import Dict, List, Union, Iterable
-from datetime import datetime
from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict
from .._types import SequenceNotStr
@@ -30,7 +29,11 @@
class SessionStartParams(TypedDict, total=False):
model_name: Required[Annotated[str, PropertyInfo(alias="modelName")]]
- """Model name to use for AI operations"""
+ """Model name to use for AI operations.
+
+ Always use the format 'provider/model-name' (e.g., 'openai/gpt-4o',
+ 'anthropic/claude-sonnet-4-5-20250929', 'google/gemini-2.0-flash')
+ """
act_timeout_ms: Annotated[float, PropertyInfo(alias="actTimeoutMs")]
"""Timeout in ms for act operations (deprecated, v2 only)"""
@@ -61,9 +64,6 @@ class SessionStartParams(TypedDict, total=False):
wait_for_captcha_solves: Annotated[bool, PropertyInfo(alias="waitForCaptchaSolves")]
"""Wait for captcha solves (deprecated, v2 only)"""
- x_sent_at: Annotated[Union[str, datetime], PropertyInfo(alias="x-sent-at", format="iso8601")]
- """ISO timestamp when request was sent"""
-
x_stream_response: Annotated[Literal["true", "false"], PropertyInfo(alias="x-stream-response")]
"""Whether to stream the response via SSE"""
@@ -113,6 +113,8 @@ class BrowserLaunchOptions(TypedDict, total=False):
locale: str
+ port: float
+
preserve_user_data_dir: Annotated[bool, PropertyInfo(alias="preserveUserDataDir")]
proxy: BrowserLaunchOptionsProxy
diff --git a/tests/api_resources/test_sessions.py b/tests/api_resources/test_sessions.py
index 473a917d..b73ae7bc 100644
--- a/tests/api_resources/test_sessions.py
+++ b/tests/api_resources/test_sessions.py
@@ -13,12 +13,12 @@
SessionActResponse,
SessionEndResponse,
SessionStartResponse,
+ SessionReplayResponse,
SessionExecuteResponse,
SessionExtractResponse,
SessionObserveResponse,
SessionNavigateResponse,
)
-from stagehand._utils import parse_datetime
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
@@ -48,7 +48,6 @@ def test_method_act_with_all_params_overload_1(self, client: Stagehand) -> None:
"variables": {"username": "john_doe"},
},
stream_response=False,
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionActResponse, session, path=["response"])
@@ -113,7 +112,6 @@ def test_method_act_with_all_params_overload_2(self, client: Stagehand) -> None:
"timeout": 30000,
"variables": {"username": "john_doe"},
},
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
session_stream.response.close()
@@ -170,8 +168,6 @@ def test_method_end(self, client: Stagehand) -> None:
def test_method_end_with_all_params(self, client: Stagehand) -> None:
session = client.sessions.end(
id="c4dbf3a9-9a58-4b22-8a1c-9f20f9f9e123",
- _force_body={},
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionEndResponse, session, path=["response"])
@@ -239,8 +235,8 @@ def test_method_execute_with_all_params_overload_1(self, client: Stagehand) -> N
"max_steps": 20,
},
frame_id="frameId",
+ should_cache=True,
stream_response=False,
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionExecuteResponse, session, path=["response"])
@@ -322,7 +318,7 @@ def test_method_execute_with_all_params_overload_2(self, client: Stagehand) -> N
},
stream_response=True,
frame_id="frameId",
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
+ should_cache=True,
x_stream_response="true",
)
session_stream.response.close()
@@ -397,7 +393,6 @@ def test_method_extract_with_all_params_overload_1(self, client: Stagehand) -> N
},
schema={"foo": "bar"},
stream_response=False,
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionExtractResponse, session, path=["response"])
@@ -459,7 +454,6 @@ def test_method_extract_with_all_params_overload_2(self, client: Stagehand) -> N
"timeout": 30000,
},
schema={"foo": "bar"},
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
session_stream.response.close()
@@ -522,7 +516,6 @@ def test_method_navigate_with_all_params(self, client: Stagehand) -> None:
"wait_until": "networkidle",
},
stream_response=True,
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionNavigateResponse, session, path=["response"])
@@ -585,7 +578,6 @@ def test_method_observe_with_all_params_overload_1(self, client: Stagehand) -> N
"timeout": 30000,
},
stream_response=False,
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionObserveResponse, session, path=["response"])
@@ -646,7 +638,6 @@ def test_method_observe_with_all_params_overload_2(self, client: Stagehand) -> N
"selector": "nav",
"timeout": 30000,
},
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
session_stream.response.close()
@@ -687,6 +678,57 @@ def test_path_params_observe_overload_2(self, client: Stagehand) -> None:
stream_response=True,
)
+ @pytest.mark.skip(reason="Prism tests are disabled")
+ @parametrize
+ def test_method_replay(self, client: Stagehand) -> None:
+ session = client.sessions.replay(
+ id="c4dbf3a9-9a58-4b22-8a1c-9f20f9f9e123",
+ )
+ assert_matches_type(SessionReplayResponse, session, path=["response"])
+
+ @pytest.mark.skip(reason="Prism tests are disabled")
+ @parametrize
+ def test_method_replay_with_all_params(self, client: Stagehand) -> None:
+ session = client.sessions.replay(
+ id="c4dbf3a9-9a58-4b22-8a1c-9f20f9f9e123",
+ x_stream_response="true",
+ )
+ assert_matches_type(SessionReplayResponse, session, path=["response"])
+
+ @pytest.mark.skip(reason="Prism tests are disabled")
+ @parametrize
+ def test_raw_response_replay(self, client: Stagehand) -> None:
+ response = client.sessions.with_raw_response.replay(
+ id="c4dbf3a9-9a58-4b22-8a1c-9f20f9f9e123",
+ )
+
+ assert response.is_closed is True
+ assert response.http_request.headers.get("X-Stainless-Lang") == "python"
+ session = response.parse()
+ assert_matches_type(SessionReplayResponse, session, path=["response"])
+
+ @pytest.mark.skip(reason="Prism tests are disabled")
+ @parametrize
+ def test_streaming_response_replay(self, client: Stagehand) -> None:
+ with client.sessions.with_streaming_response.replay(
+ id="c4dbf3a9-9a58-4b22-8a1c-9f20f9f9e123",
+ ) as response:
+ assert not response.is_closed
+ assert response.http_request.headers.get("X-Stainless-Lang") == "python"
+
+ session = response.parse()
+ assert_matches_type(SessionReplayResponse, session, path=["response"])
+
+ assert cast(Any, response.is_closed) is True
+
+ @pytest.mark.skip(reason="Prism tests are disabled")
+ @parametrize
+ def test_path_params_replay(self, client: Stagehand) -> None:
+ with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"):
+ client.sessions.with_raw_response.replay(
+ id="",
+ )
+
@pytest.mark.skip(reason="Prism tests are disabled")
@parametrize
def test_method_start(self, client: Stagehand) -> None:
@@ -718,6 +760,7 @@ def test_method_start_with_all_params(self, client: Stagehand) -> None:
"ignore_default_args": True,
"ignore_https_errors": True,
"locale": "locale",
+ "port": 0,
"preserve_user_data_dir": True,
"proxy": {
"server": "server",
@@ -778,7 +821,6 @@ def test_method_start_with_all_params(self, client: Stagehand) -> None:
system_prompt="systemPrompt",
verbose=1,
wait_for_captcha_solves=True,
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionStartResponse, session, path=["response"])
@@ -837,7 +879,6 @@ async def test_method_act_with_all_params_overload_1(self, async_client: AsyncSt
"variables": {"username": "john_doe"},
},
stream_response=False,
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionActResponse, session, path=["response"])
@@ -902,7 +943,6 @@ async def test_method_act_with_all_params_overload_2(self, async_client: AsyncSt
"timeout": 30000,
"variables": {"username": "john_doe"},
},
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
await session_stream.response.aclose()
@@ -959,8 +999,6 @@ async def test_method_end(self, async_client: AsyncStagehand) -> None:
async def test_method_end_with_all_params(self, async_client: AsyncStagehand) -> None:
session = await async_client.sessions.end(
id="c4dbf3a9-9a58-4b22-8a1c-9f20f9f9e123",
- _force_body={},
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionEndResponse, session, path=["response"])
@@ -1028,8 +1066,8 @@ async def test_method_execute_with_all_params_overload_1(self, async_client: Asy
"max_steps": 20,
},
frame_id="frameId",
+ should_cache=True,
stream_response=False,
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionExecuteResponse, session, path=["response"])
@@ -1111,7 +1149,7 @@ async def test_method_execute_with_all_params_overload_2(self, async_client: Asy
},
stream_response=True,
frame_id="frameId",
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
+ should_cache=True,
x_stream_response="true",
)
await session_stream.response.aclose()
@@ -1186,7 +1224,6 @@ async def test_method_extract_with_all_params_overload_1(self, async_client: Asy
},
schema={"foo": "bar"},
stream_response=False,
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionExtractResponse, session, path=["response"])
@@ -1248,7 +1285,6 @@ async def test_method_extract_with_all_params_overload_2(self, async_client: Asy
"timeout": 30000,
},
schema={"foo": "bar"},
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
await session_stream.response.aclose()
@@ -1311,7 +1347,6 @@ async def test_method_navigate_with_all_params(self, async_client: AsyncStagehan
"wait_until": "networkidle",
},
stream_response=True,
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionNavigateResponse, session, path=["response"])
@@ -1374,7 +1409,6 @@ async def test_method_observe_with_all_params_overload_1(self, async_client: Asy
"timeout": 30000,
},
stream_response=False,
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionObserveResponse, session, path=["response"])
@@ -1435,7 +1469,6 @@ async def test_method_observe_with_all_params_overload_2(self, async_client: Asy
"selector": "nav",
"timeout": 30000,
},
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
await session_stream.response.aclose()
@@ -1476,6 +1509,57 @@ async def test_path_params_observe_overload_2(self, async_client: AsyncStagehand
stream_response=True,
)
+ @pytest.mark.skip(reason="Prism tests are disabled")
+ @parametrize
+ async def test_method_replay(self, async_client: AsyncStagehand) -> None:
+ session = await async_client.sessions.replay(
+ id="c4dbf3a9-9a58-4b22-8a1c-9f20f9f9e123",
+ )
+ assert_matches_type(SessionReplayResponse, session, path=["response"])
+
+ @pytest.mark.skip(reason="Prism tests are disabled")
+ @parametrize
+ async def test_method_replay_with_all_params(self, async_client: AsyncStagehand) -> None:
+ session = await async_client.sessions.replay(
+ id="c4dbf3a9-9a58-4b22-8a1c-9f20f9f9e123",
+ x_stream_response="true",
+ )
+ assert_matches_type(SessionReplayResponse, session, path=["response"])
+
+ @pytest.mark.skip(reason="Prism tests are disabled")
+ @parametrize
+ async def test_raw_response_replay(self, async_client: AsyncStagehand) -> None:
+ response = await async_client.sessions.with_raw_response.replay(
+ id="c4dbf3a9-9a58-4b22-8a1c-9f20f9f9e123",
+ )
+
+ assert response.is_closed is True
+ assert response.http_request.headers.get("X-Stainless-Lang") == "python"
+ session = await response.parse()
+ assert_matches_type(SessionReplayResponse, session, path=["response"])
+
+ @pytest.mark.skip(reason="Prism tests are disabled")
+ @parametrize
+ async def test_streaming_response_replay(self, async_client: AsyncStagehand) -> None:
+ async with async_client.sessions.with_streaming_response.replay(
+ id="c4dbf3a9-9a58-4b22-8a1c-9f20f9f9e123",
+ ) as response:
+ assert not response.is_closed
+ assert response.http_request.headers.get("X-Stainless-Lang") == "python"
+
+ session = await response.parse()
+ assert_matches_type(SessionReplayResponse, session, path=["response"])
+
+ assert cast(Any, response.is_closed) is True
+
+ @pytest.mark.skip(reason="Prism tests are disabled")
+ @parametrize
+ async def test_path_params_replay(self, async_client: AsyncStagehand) -> None:
+ with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"):
+ await async_client.sessions.with_raw_response.replay(
+ id="",
+ )
+
@pytest.mark.skip(reason="Prism tests are disabled")
@parametrize
async def test_method_start(self, async_client: AsyncStagehand) -> None:
@@ -1507,6 +1591,7 @@ async def test_method_start_with_all_params(self, async_client: AsyncStagehand)
"ignore_default_args": True,
"ignore_https_errors": True,
"locale": "locale",
+ "port": 0,
"preserve_user_data_dir": True,
"proxy": {
"server": "server",
@@ -1567,7 +1652,6 @@ async def test_method_start_with_all_params(self, async_client: AsyncStagehand)
system_prompt="systemPrompt",
verbose=1,
wait_for_captcha_solves=True,
- x_sent_at=parse_datetime("2025-01-15T10:30:00Z"),
x_stream_response="true",
)
assert_matches_type(SessionStartResponse, session, path=["response"])
diff --git a/tests/test_client.py b/tests/test_client.py
index d57cbeac..85bb6207 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -8,10 +8,11 @@
import json
import asyncio
import inspect
+import dataclasses
import tracemalloc
-from typing import Any, Union, cast
+from typing import Any, Union, TypeVar, Callable, Iterable, Iterator, Optional, Coroutine, cast
from unittest import mock
-from typing_extensions import Literal
+from typing_extensions import Literal, AsyncIterator, override
import httpx
import pytest
@@ -37,6 +38,7 @@
from .utils import update_env
+T = TypeVar("T")
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
browserbase_api_key = "My Browserbase API Key"
browserbase_project_id = "My Browserbase Project ID"
@@ -53,6 +55,57 @@ def _low_retry_timeout(*_args: Any, **_kwargs: Any) -> float:
return 0.1
+def mirror_request_content(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, content=request.content)
+
+
+# note: we can't use the httpx.MockTransport class as it consumes the request
+# body itself, which means we can't test that the body is read lazily
+class MockTransport(httpx.BaseTransport, httpx.AsyncBaseTransport):
+ def __init__(
+ self,
+ handler: Callable[[httpx.Request], httpx.Response]
+ | Callable[[httpx.Request], Coroutine[Any, Any, httpx.Response]],
+ ) -> None:
+ self.handler = handler
+
+ @override
+ def handle_request(
+ self,
+ request: httpx.Request,
+ ) -> httpx.Response:
+ assert not inspect.iscoroutinefunction(self.handler), "handler must not be a coroutine function"
+ assert inspect.isfunction(self.handler), "handler must be a function"
+ return self.handler(request)
+
+ @override
+ async def handle_async_request(
+ self,
+ request: httpx.Request,
+ ) -> httpx.Response:
+ assert inspect.iscoroutinefunction(self.handler), "handler must be a coroutine function"
+ return await self.handler(request)
+
+
+@dataclasses.dataclass
+class Counter:
+ value: int = 0
+
+
+def _make_sync_iterator(iterable: Iterable[T], counter: Optional[Counter] = None) -> Iterator[T]:
+ for item in iterable:
+ if counter:
+ counter.value += 1
+ yield item
+
+
+async def _make_async_iterator(iterable: Iterable[T], counter: Optional[Counter] = None) -> AsyncIterator[T]:
+ for item in iterable:
+ if counter:
+ counter.value += 1
+ yield item
+
+
def _get_open_connections(client: Stagehand | AsyncStagehand) -> int:
transport = client._client._transport
assert isinstance(transport, httpx.HTTPTransport) or isinstance(transport, httpx.AsyncHTTPTransport)
@@ -579,6 +632,72 @@ def test_multipart_repeating_array(self, client: Stagehand) -> None:
b"",
]
+ @pytest.mark.respx(base_url=base_url)
+ def test_binary_content_upload(self, respx_mock: MockRouter, client: Stagehand) -> None:
+ respx_mock.post("/upload").mock(side_effect=mirror_request_content)
+
+ file_content = b"Hello, this is a test file."
+
+ response = client.post(
+ "/upload",
+ content=file_content,
+ cast_to=httpx.Response,
+ options={"headers": {"Content-Type": "application/octet-stream"}},
+ )
+
+ assert response.status_code == 200
+ assert response.request.headers["Content-Type"] == "application/octet-stream"
+ assert response.content == file_content
+
+ def test_binary_content_upload_with_iterator(self) -> None:
+ file_content = b"Hello, this is a test file."
+ counter = Counter()
+ iterator = _make_sync_iterator([file_content], counter=counter)
+
+ def mock_handler(request: httpx.Request) -> httpx.Response:
+ assert counter.value == 0, "the request body should not have been read"
+ return httpx.Response(200, content=request.read())
+
+ with Stagehand(
+ base_url=base_url,
+ browserbase_api_key=browserbase_api_key,
+ browserbase_project_id=browserbase_project_id,
+ model_api_key=model_api_key,
+ _strict_response_validation=True,
+ http_client=httpx.Client(transport=MockTransport(handler=mock_handler)),
+ ) as client:
+ response = client.post(
+ "/upload",
+ content=iterator,
+ cast_to=httpx.Response,
+ options={"headers": {"Content-Type": "application/octet-stream"}},
+ )
+
+ assert response.status_code == 200
+ assert response.request.headers["Content-Type"] == "application/octet-stream"
+ assert response.content == file_content
+ assert counter.value == 1
+
+ @pytest.mark.respx(base_url=base_url)
+ def test_binary_content_upload_with_body_is_deprecated(self, respx_mock: MockRouter, client: Stagehand) -> None:
+ respx_mock.post("/upload").mock(side_effect=mirror_request_content)
+
+ file_content = b"Hello, this is a test file."
+
+ with pytest.deprecated_call(
+ match="Passing raw bytes as `body` is deprecated and will be removed in a future version. Please pass raw bytes via the `content` parameter instead."
+ ):
+ response = client.post(
+ "/upload",
+ body=file_content,
+ cast_to=httpx.Response,
+ options={"headers": {"Content-Type": "application/octet-stream"}},
+ )
+
+ assert response.status_code == 200
+ assert response.request.headers["Content-Type"] == "application/octet-stream"
+ assert response.content == file_content
+
@pytest.mark.respx(base_url=base_url)
def test_basic_union_response(self, respx_mock: MockRouter, client: Stagehand) -> None:
class Model1(BaseModel):
@@ -1553,6 +1672,74 @@ def test_multipart_repeating_array(self, async_client: AsyncStagehand) -> None:
b"",
]
+ @pytest.mark.respx(base_url=base_url)
+ async def test_binary_content_upload(self, respx_mock: MockRouter, async_client: AsyncStagehand) -> None:
+ respx_mock.post("/upload").mock(side_effect=mirror_request_content)
+
+ file_content = b"Hello, this is a test file."
+
+ response = await async_client.post(
+ "/upload",
+ content=file_content,
+ cast_to=httpx.Response,
+ options={"headers": {"Content-Type": "application/octet-stream"}},
+ )
+
+ assert response.status_code == 200
+ assert response.request.headers["Content-Type"] == "application/octet-stream"
+ assert response.content == file_content
+
+ async def test_binary_content_upload_with_asynciterator(self) -> None:
+ file_content = b"Hello, this is a test file."
+ counter = Counter()
+ iterator = _make_async_iterator([file_content], counter=counter)
+
+ async def mock_handler(request: httpx.Request) -> httpx.Response:
+ assert counter.value == 0, "the request body should not have been read"
+ return httpx.Response(200, content=await request.aread())
+
+ async with AsyncStagehand(
+ base_url=base_url,
+ browserbase_api_key=browserbase_api_key,
+ browserbase_project_id=browserbase_project_id,
+ model_api_key=model_api_key,
+ _strict_response_validation=True,
+ http_client=httpx.AsyncClient(transport=MockTransport(handler=mock_handler)),
+ ) as client:
+ response = await client.post(
+ "/upload",
+ content=iterator,
+ cast_to=httpx.Response,
+ options={"headers": {"Content-Type": "application/octet-stream"}},
+ )
+
+ assert response.status_code == 200
+ assert response.request.headers["Content-Type"] == "application/octet-stream"
+ assert response.content == file_content
+ assert counter.value == 1
+
+ @pytest.mark.respx(base_url=base_url)
+ async def test_binary_content_upload_with_body_is_deprecated(
+ self, respx_mock: MockRouter, async_client: AsyncStagehand
+ ) -> None:
+ respx_mock.post("/upload").mock(side_effect=mirror_request_content)
+
+ file_content = b"Hello, this is a test file."
+
+ with pytest.deprecated_call(
+ match="Passing raw bytes as `body` is deprecated and will be removed in a future version. Please pass raw bytes via the `content` parameter instead."
+ ):
+ response = await async_client.post(
+ "/upload",
+ body=file_content,
+ cast_to=httpx.Response,
+ options={"headers": {"Content-Type": "application/octet-stream"}},
+ )
+
+ assert response.status_code == 200
+ assert response.request.headers["Content-Type"] == "application/octet-stream"
+ assert response.content == file_content
+
@pytest.mark.respx(base_url=base_url)
async def test_basic_union_response(self, respx_mock: MockRouter, async_client: AsyncStagehand) -> None:
class Model1(BaseModel):
diff --git a/uv.lock b/uv.lock
index a7f085f0..d7283983 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1359,7 +1359,7 @@ wheels = [
[[package]]
name = "stagehand"
-version = "3.4.7"
+version = "3.4.8"
source = { editable = "." }
dependencies = [
{ name = "anyio" },