aether-browser 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,124 @@
1
+ # aether-browser
2
+
3
+ Client and CLI for **[Agent Browser](https://github.com/AetherAI3/agent-browser) by Aether AI** —
4
+ self-hosted Chrome for AI agents. Drive one browser session through a closed HTTP API, and watch or
5
+ take over that exact same session through noVNC.
6
+
7
+ ```bash
8
+ npm install aether-browser
9
+ ```
10
+
11
+ Zero runtime dependencies. Ships TypeScript types. Node 18+.
12
+
13
+ ## Drive a session
14
+
15
+ `withSession` always attempts to end the session, including when your callback throws, so a crash
16
+ cannot leave the single session slot occupied.
17
+
18
+ ```ts
19
+ import { AgentBrowser, withSession } from 'aether-browser'
20
+
21
+ const browser = new AgentBrowser({
22
+ baseUrl: 'http://127.0.0.1:8092',
23
+ controllerToken: process.env.AGENT_BROWSER_CONTROLLER_TOKEN,
24
+ })
25
+
26
+ await withSession(browser, async (session) => {
27
+ console.log('watch it live at', session.viewUrl)
28
+
29
+ const page = await session.navigate('https://example.com')
30
+ console.log(page.title, page.readable_text.slice(0, 200))
31
+
32
+ await session.click({ selector: '#login' })
33
+ await session.type({ selector: '#user', text: 'ada' })
34
+ await session.press('Enter')
35
+
36
+ const shot = await session.snapshot()
37
+ console.log(`${shot.vision_steps_remaining} vision steps left`)
38
+ })
39
+ ```
40
+
41
+ Connection settings fall back to `AGENT_BROWSER_URL`, `AGENT_BROWSER_CONTROLLER_TOKEN`, and
42
+ `AGENT_BROWSER_OBSERVER_TOKEN`, so `new AgentBrowser()` works with no arguments in a configured
43
+ environment.
44
+
45
+ ## Two roles, kept separate
46
+
47
+ The server splits authority, and this client keeps that split visible in your code. The observer
48
+ token covers health and snapshot; the controller token is required to create, navigate, interact,
49
+ and end. Give a read-only caller only the observer token:
50
+
51
+ ```ts
52
+ const readOnly = new AgentBrowser({ observerToken: process.env.AGENT_BROWSER_OBSERVER_TOKEN })
53
+ await readOnly.health()
54
+ ```
55
+
56
+ ## Errors
57
+
58
+ Failures raise `AgentBrowserError` carrying the server's stable `code`:
59
+
60
+ ```ts
61
+ import { AgentBrowserError } from 'aether-browser'
62
+
63
+ try {
64
+ await browser.createSession()
65
+ } catch (error) {
66
+ if (error instanceof AgentBrowserError && error.isCapacityReached) {
67
+ console.log(`busy; retry in ${error.retryAfterSeconds}s`)
68
+ }
69
+ }
70
+ ```
71
+
72
+ Codes are `AUTH_REQUIRED`, `AUTH_FORBIDDEN`, `SESSION_CAPACITY_REACHED`, `SESSION_NOT_FOUND`,
73
+ `SESSION_EXPIRED`, `VISION_BUDGET_EXHAUSTED`, `INVALID_URL`, `DESTINATION_BLOCKED`,
74
+ `INVALID_INTERACTION`, `BROWSER_NOT_READY`, and `INTERNAL_ERROR`. A transport failure raises the
75
+ same class with `code` left `undefined`, so a refused connection is never mistaken for a refusal
76
+ by the server.
77
+
78
+ ## CLI
79
+
80
+ ```bash
81
+ npx aether-browser doctor # check Docker, platform, and server health; say what is wrong
82
+ npx aether-browser up # build and start the runtime
83
+ npx aether-browser status # print the health document
84
+ npx aether-browser open # open the live noVNC view
85
+ npx aether-browser down # stop and clean up
86
+ ```
87
+
88
+ Run `doctor` first. It checks the things that actually break a first run and tells you which one
89
+ failed, instead of leaving you to read a build log.
90
+
91
+ ### What `up` really does, and its limits
92
+
93
+ Agent Browser publishes **no Chrome-containing image** — distribution is source-only. So `up` builds
94
+ the image locally from source, and **the first build takes several minutes** because it installs a
95
+ hash-locked Python environment and the current Google Chrome Stable package. It uses the checkout
96
+ you are standing in if there is one, and otherwise downloads the matching tagged source tarball from
97
+ the official repository over HTTPS into your cache directory.
98
+
99
+ `up` requires **Linux** with Docker Compose v2. The documented quickstart uses Docker host
100
+ networking so both the API and the noVNC listeners stay bound to numeric loopback; Docker Desktop on
101
+ macOS and Windows is outside that contract, and `doctor` will tell you so rather than half-working.
102
+
103
+ **The library has no such limit.** It is plain HTTP and runs anywhere Node does — point it at a
104
+ server on a Linux host and drive it from macOS, Windows, or CI.
105
+
106
+ ## Security
107
+
108
+ The v0.1 noVNC surface is **unauthenticated** and intended for numeric loopback on a machine you
109
+ control. Treat every process and user that can reach that loopback interface as trusted with the
110
+ live browser view. Do not expose it through a tunnel, reverse proxy, or container bridge. See the
111
+ [security model](https://github.com/AetherAI3/agent-browser/blob/main/docs/SECURITY-MODEL.md).
112
+
113
+ The API is deliberately closed: `click`, `type`, `scroll`, and `press` are the only interactions,
114
+ and there is no arbitrary JavaScript, CDP, upload, clipboard, download, extension, shell,
115
+ filesystem, credential, or cookie field. This client cannot widen that surface, because the server
116
+ rejects unknown fields.
117
+
118
+ ## Status
119
+
120
+ `0.1.0-rc.1` tracks Agent Browser `v0.1.0-rc.1` and its `api_version: "v1"` contract. This is a
121
+ release candidate: the API may change before `v0.1.0`. Issues and design discussion are welcome on
122
+ [the repository](https://github.com/AetherAI3/agent-browser/issues).
123
+
124
+ Apache-2.0 · [Aether AI](https://github.com/AetherAI3)
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "aether-browser",
3
+ "version": "0.1.0-rc.1",
4
+ "description": "Client and CLI for Agent Browser by Aether AI: drive one self-hosted Chrome session over a closed HTTP API and watch or take over that same session through noVNC.",
5
+ "license": "Apache-2.0",
6
+ "author": "Aether AI",
7
+ "type": "module",
8
+ "engines": {
9
+ "node": ">=18"
10
+ },
11
+ "main": "./src/index.js",
12
+ "types": "./src/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./src/index.d.ts",
16
+ "default": "./src/index.js"
17
+ },
18
+ "./package.json": "./package.json"
19
+ },
20
+ "bin": {
21
+ "aether-browser": "src/cli.js"
22
+ },
23
+ "files": [
24
+ "src",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "sideEffects": false,
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/AetherAI3/agent-browser.git",
32
+ "directory": "clients/node"
33
+ },
34
+ "homepage": "https://github.com/AetherAI3/agent-browser#readme",
35
+ "bugs": {
36
+ "url": "https://github.com/AetherAI3/agent-browser/issues"
37
+ },
38
+ "keywords": [
39
+ "agent-browser",
40
+ "browser",
41
+ "automation",
42
+ "ai-agents",
43
+ "chrome",
44
+ "novnc",
45
+ "self-hosted",
46
+ "human-in-the-loop",
47
+ "computer-use"
48
+ ],
49
+ "scripts": {
50
+ "test": "node --test test/client.test.js",
51
+ "typecheck": "tsc --noEmit -p tsconfig.json"
52
+ },
53
+ "devDependencies": {
54
+ "typescript": "5.9.3"
55
+ },
56
+ "publishConfig": {
57
+ "access": "public",
58
+ "provenance": true
59
+ }
60
+ }
package/src/cli.js ADDED
@@ -0,0 +1,306 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * aether-browser CLI.
4
+ *
5
+ * The runtime is a container you build from source: Agent Browser publishes no
6
+ * Chrome-containing image, so `up` builds one locally the first time and that build
7
+ * takes several minutes. This CLI never pretends otherwise.
8
+ */
9
+
10
+ import { spawnSync } from 'node:child_process'
11
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
12
+ import { homedir, platform } from 'node:os'
13
+ import { dirname, join, resolve } from 'node:path'
14
+ import { fileURLToPath } from 'node:url'
15
+
16
+ import { AgentBrowser, AgentBrowserError, DEFAULT_BASE_URL } from './index.js'
17
+
18
+ const HERE = dirname(fileURLToPath(import.meta.url))
19
+ const PKG = JSON.parse(readFileSync(join(HERE, '..', 'package.json'), 'utf8'))
20
+ const REPO = 'https://github.com/AetherAI3/agent-browser'
21
+ const NOVNC_URL = 'http://127.0.0.1:6080/vnc.html'
22
+
23
+ const styles = { on: process.stdout.isTTY && !process.env.NO_COLOR }
24
+ const dim = (s) => (styles.on ? `\u001b[2m${s}\u001b[0m` : s)
25
+ const bold = (s) => (styles.on ? `\u001b[1m${s}\u001b[0m` : s)
26
+ const red = (s) => (styles.on ? `\u001b[31m${s}\u001b[0m` : s)
27
+ const green = (s) => (styles.on ? `\u001b[32m${s}\u001b[0m` : s)
28
+ const yellow = (s) => (styles.on ? `\u001b[33m${s}\u001b[0m` : s)
29
+
30
+ const ok = (s) => console.log(` ${green('ok')} ${s}`)
31
+ const warn = (s) => console.log(` ${yellow('warn')} ${s}`)
32
+ const bad = (s) => console.log(` ${red('fail')} ${s}`)
33
+
34
+ function run(cmd, args, options = {}) {
35
+ return spawnSync(cmd, args, { encoding: 'utf8', ...options })
36
+ }
37
+
38
+ function has(cmd) {
39
+ const probe = run(cmd, ['--version'])
40
+ return probe.status === 0 ? (probe.stdout || probe.stderr).trim().split('\n')[0] : undefined
41
+ }
42
+
43
+ function composeCommand() {
44
+ const v2 = run('docker', ['compose', 'version'])
45
+ if (v2.status === 0) return { cmd: 'docker', args: ['compose'], version: v2.stdout.trim() }
46
+ return undefined
47
+ }
48
+
49
+ /** Locate a checkout: the current tree if it is one, otherwise the cached release tarball. */
50
+ function findComposeDir({ allowDownload }) {
51
+ let dir = process.cwd()
52
+ for (let depth = 0; depth < 6; depth++) {
53
+ if (existsSync(join(dir, 'docker-compose.yml')) && existsSync(join(dir, 'Dockerfile'))) {
54
+ return { dir, source: 'local checkout' }
55
+ }
56
+ const parent = dirname(dir)
57
+ if (parent === dir) break
58
+ dir = parent
59
+ }
60
+ if (!allowDownload) return undefined
61
+
62
+ const version = PKG.version
63
+ const cacheRoot = join(process.env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'aether-browser')
64
+ const target = join(cacheRoot, `agent-browser-${version}`)
65
+ if (existsSync(join(target, 'docker-compose.yml'))) {
66
+ return { dir: target, source: `cached source ${dim(target)}` }
67
+ }
68
+
69
+ const url = `${REPO}/archive/refs/tags/v${version}.tar.gz`
70
+ console.log(` fetching source ${dim(url)}`)
71
+ mkdirSync(target, { recursive: true })
72
+ const tarball = join(cacheRoot, `v${version}.tar.gz`)
73
+ const curl = run('curl', ['-fsSL', '--proto', '=https', '--tlsv1.2', '-o', tarball, url], {
74
+ stdio: 'inherit',
75
+ })
76
+ if (curl.status !== 0) {
77
+ rmSync(target, { recursive: true, force: true })
78
+ return undefined
79
+ }
80
+ const untar = run('tar', ['-xzf', tarball, '-C', target, '--strip-components=1'], {
81
+ stdio: 'inherit',
82
+ })
83
+ rmSync(tarball, { force: true })
84
+ if (untar.status !== 0) {
85
+ rmSync(target, { recursive: true, force: true })
86
+ return undefined
87
+ }
88
+ return { dir: target, source: `downloaded source ${dim(target)}` }
89
+ }
90
+
91
+ function preflight({ forUp }) {
92
+ const problems = []
93
+
94
+ console.log(bold('\nEnvironment'))
95
+ console.log(` node ${process.version}`)
96
+ console.log(` client aether-browser ${PKG.version}`)
97
+ console.log(` os ${platform()}`)
98
+
99
+ console.log(bold('\nRuntime prerequisites'))
100
+ if (platform() === 'linux') {
101
+ ok('Linux host')
102
+ } else {
103
+ bad(
104
+ `the documented quickstart is Linux only (found ${platform()}). It relies on Docker host ` +
105
+ `networking so both listeners stay on numeric loopback; Docker Desktop is outside that contract.`,
106
+ )
107
+ problems.push(
108
+ 'Run the container on a Linux host. The client library itself works on any platform ' +
109
+ 'against a server you can reach.',
110
+ )
111
+ }
112
+
113
+ const docker = has('docker')
114
+ if (docker) ok(docker)
115
+ else {
116
+ bad('docker not found on PATH')
117
+ problems.push('Install Docker Engine: https://docs.docker.com/engine/install/')
118
+ }
119
+
120
+ const compose = docker ? composeCommand() : undefined
121
+ if (compose) ok(compose.version)
122
+ else if (docker) {
123
+ bad('docker compose v2 not available')
124
+ problems.push('Install the Docker Compose v2 plugin.')
125
+ }
126
+
127
+ if (docker) {
128
+ const info = run('docker', ['info', '--format', '{{.ServerVersion}}'])
129
+ if (info.status === 0) ok(`docker daemon reachable (server ${info.stdout.trim()})`)
130
+ else {
131
+ bad('docker daemon is not reachable')
132
+ problems.push('Start Docker, or add your user to the docker group and re-login.')
133
+ }
134
+ }
135
+
136
+ if (forUp) {
137
+ console.log(bold('\nSource'))
138
+ const found = findComposeDir({ allowDownload: false })
139
+ if (found) ok(`docker-compose.yml found in ${found.source} ${dim(found.dir)}`)
140
+ else warn(`no checkout here; \`up\` will download ${REPO} at v${PKG.version}`)
141
+ }
142
+
143
+ return problems
144
+ }
145
+
146
+ async function probeHealth(baseUrl) {
147
+ const browser = new AgentBrowser({ baseUrl, timeoutMs: 4000 })
148
+ try {
149
+ return { health: await browser.health() }
150
+ } catch (error) {
151
+ return { error }
152
+ }
153
+ }
154
+
155
+ async function cmdDoctor() {
156
+ const problems = preflight({ forUp: true })
157
+
158
+ console.log(bold('\nServer'))
159
+ const baseUrl = process.env.AGENT_BROWSER_URL || DEFAULT_BASE_URL
160
+ const { health, error } = await probeHealth(baseUrl)
161
+ if (health) {
162
+ ok(`${baseUrl} responding (version ${health.version})`)
163
+ console.log(
164
+ ` browser_ready=${health.browser_ready} session_active=${health.session_active} ` +
165
+ `slots_available=${health.slots_available}`,
166
+ )
167
+ } else {
168
+ warn(`${baseUrl} not responding yet ${dim(`(${error?.message ?? 'unknown'})`)}`)
169
+ console.log(` start it with ${bold('npx aether-browser up')}`)
170
+ }
171
+
172
+ console.log(bold('\nTokens'))
173
+ if (process.env.AGENT_BROWSER_CONTROLLER_TOKEN) ok('AGENT_BROWSER_CONTROLLER_TOKEN is set')
174
+ else warn('AGENT_BROWSER_CONTROLLER_TOKEN unset (fine for strict loopback local mode)')
175
+
176
+ if (problems.length) {
177
+ console.log(bold(red('\nBlocking problems')))
178
+ for (const problem of problems) console.log(` - ${problem}`)
179
+ console.log()
180
+ return 1
181
+ }
182
+ console.log(green('\nReady.\n'))
183
+ return 0
184
+ }
185
+
186
+ function cmdUp(argv) {
187
+ const problems = preflight({ forUp: false })
188
+ if (problems.length) {
189
+ console.log(bold(red('\nCannot start')))
190
+ for (const problem of problems) console.log(` - ${problem}`)
191
+ console.log()
192
+ return 1
193
+ }
194
+
195
+ console.log(bold('\nSource'))
196
+ const found = findComposeDir({ allowDownload: true })
197
+ if (!found) {
198
+ console.error(red('\nCould not obtain a source checkout to build from.\n'))
199
+ return 1
200
+ }
201
+ ok(found.source)
202
+
203
+ console.log(bold('\nBuilding and starting'))
204
+ console.log(
205
+ dim(
206
+ ' The first build installs a hash-locked Python environment and the current\n' +
207
+ ' Google Chrome Stable package, so it can take several minutes.\n',
208
+ ),
209
+ )
210
+ const detach = !argv.includes('--foreground')
211
+ const args = ['compose', 'up', '--build', ...(detach ? ['--detach'] : [])]
212
+ const result = run('docker', args, { cwd: found.dir, stdio: 'inherit' })
213
+ if (result.status !== 0) return result.status ?? 1
214
+
215
+ if (detach) {
216
+ console.log(`\n API ${DEFAULT_BASE_URL}/browser/health`)
217
+ console.log(` noVNC ${NOVNC_URL}`)
218
+ console.log(dim(`\n Stop with: npx aether-browser down\n`))
219
+ }
220
+ return 0
221
+ }
222
+
223
+ function cmdDown() {
224
+ const found = findComposeDir({ allowDownload: false })
225
+ if (!found) {
226
+ console.error(red('No checkout found here. Run `down` from the directory you ran `up` in.'))
227
+ return 1
228
+ }
229
+ const result = run('docker', ['compose', 'down', '--volumes', '--remove-orphans'], {
230
+ cwd: found.dir,
231
+ stdio: 'inherit',
232
+ })
233
+ return result.status ?? 1
234
+ }
235
+
236
+ async function cmdStatus() {
237
+ const baseUrl = process.env.AGENT_BROWSER_URL || DEFAULT_BASE_URL
238
+ const { health, error } = await probeHealth(baseUrl)
239
+ if (!health) {
240
+ console.error(red(`Agent Browser is not responding at ${baseUrl}`))
241
+ if (error instanceof AgentBrowserError && error.code) console.error(dim(` ${error.code}`))
242
+ return 1
243
+ }
244
+ console.log(JSON.stringify(health, null, 2))
245
+ return 0
246
+ }
247
+
248
+ function cmdOpen() {
249
+ const opener =
250
+ platform() === 'darwin' ? 'open' : platform() === 'win32' ? 'explorer' : 'xdg-open'
251
+ console.log(`Opening ${NOVNC_URL}`)
252
+ const result = run(opener, [NOVNC_URL], { stdio: 'ignore' })
253
+ if (result.status !== 0) console.log(`Open it manually: ${NOVNC_URL}`)
254
+ return 0
255
+ }
256
+
257
+ function usage() {
258
+ console.log(`
259
+ ${bold('aether-browser')} ${dim(PKG.version)}
260
+ Client and CLI for Agent Browser by Aether AI.
261
+
262
+ ${bold('Usage')}
263
+ npx aether-browser <command>
264
+
265
+ ${bold('Commands')}
266
+ doctor Check Docker, platform, ports, and server health, and say what is wrong
267
+ up Build and start the runtime (Linux + Docker Compose v2; first build is slow)
268
+ down Stop the runtime and remove its volumes
269
+ status Print the server health document as JSON
270
+ open Open the live noVNC view in a browser
271
+ help Show this message
272
+
273
+ ${bold('Environment')}
274
+ AGENT_BROWSER_URL Server base URL (default ${DEFAULT_BASE_URL})
275
+ AGENT_BROWSER_CONTROLLER_TOKEN Controller token, if the server runs authenticated
276
+ AGENT_BROWSER_OBSERVER_TOKEN Observer token
277
+
278
+ ${bold('Library')}
279
+ import { AgentBrowser, withSession } from 'aether-browser'
280
+
281
+ ${dim(REPO)}
282
+ `)
283
+ return 0
284
+ }
285
+
286
+ const [, , command = 'help', ...rest] = process.argv
287
+ const commands = {
288
+ doctor: cmdDoctor,
289
+ up: () => cmdUp(rest),
290
+ down: cmdDown,
291
+ status: cmdStatus,
292
+ open: cmdOpen,
293
+ help: usage,
294
+ '--help': usage,
295
+ '-h': usage,
296
+ '--version': () => (console.log(PKG.version), 0),
297
+ '-v': () => (console.log(PKG.version), 0),
298
+ }
299
+
300
+ const handler = commands[command]
301
+ if (!handler) {
302
+ console.error(red(`Unknown command: ${command}`))
303
+ usage()
304
+ process.exit(1)
305
+ }
306
+ process.exit((await handler()) ?? 0)
package/src/index.d.ts ADDED
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Types for the Agent Browser v1 API client.
3
+ *
4
+ * These mirror the closed server models in `src/agent_browser/models.py`. The server
5
+ * rejects unknown fields, so these types are deliberately exact rather than permissive.
6
+ */
7
+
8
+ export declare const API_VERSION: 'v1'
9
+ export declare const DEFAULT_BASE_URL: 'http://127.0.0.1:8092'
10
+
11
+ export type AllowedKey =
12
+ | 'Enter'
13
+ | 'Escape'
14
+ | 'Tab'
15
+ | 'Backspace'
16
+ | 'Delete'
17
+ | 'Space'
18
+ | 'ArrowUp'
19
+ | 'ArrowDown'
20
+ | 'ArrowLeft'
21
+ | 'ArrowRight'
22
+ | 'Home'
23
+ | 'End'
24
+ | 'PageUp'
25
+ | 'PageDown'
26
+ | 'Control+A'
27
+ | 'Control+Z'
28
+ | 'Control+Shift+Z'
29
+ | 'Meta+A'
30
+ | 'Meta+Z'
31
+ | 'Meta+Shift+Z'
32
+
33
+ export declare const ALLOWED_KEYS: readonly AllowedKey[]
34
+
35
+ export type ErrorCode =
36
+ | 'AUTH_REQUIRED'
37
+ | 'AUTH_FORBIDDEN'
38
+ | 'SESSION_CAPACITY_REACHED'
39
+ | 'SESSION_NOT_FOUND'
40
+ | 'SESSION_EXPIRED'
41
+ | 'VISION_BUDGET_EXHAUSTED'
42
+ | 'INVALID_URL'
43
+ | 'DESTINATION_BLOCKED'
44
+ | 'INVALID_INTERACTION'
45
+ | 'BROWSER_NOT_READY'
46
+ | 'INTERNAL_ERROR'
47
+
48
+ export type InteractionAction = 'click' | 'type' | 'scroll' | 'press'
49
+
50
+ export interface AccessibilityNode {
51
+ role: string
52
+ name: string
53
+ value: string
54
+ focused: boolean
55
+ disabled: boolean
56
+ }
57
+
58
+ export interface AccessibilitySnapshot {
59
+ nodes: AccessibilityNode[]
60
+ truncated: boolean
61
+ }
62
+
63
+ export interface Viewport {
64
+ width: number
65
+ height: number
66
+ device_scale_factor: number
67
+ }
68
+
69
+ export interface HealthResponse {
70
+ api_version: 'v1'
71
+ status: 'ok'
72
+ version: string
73
+ browser_ready: boolean
74
+ session_active: boolean
75
+ slots_available: number
76
+ started_at: string
77
+ }
78
+
79
+ export interface CreateSessionResponse {
80
+ api_version: 'v1'
81
+ status: 'created'
82
+ session_id: string
83
+ state: 'active'
84
+ max_vision_steps: number
85
+ view_url: string
86
+ created_at: string
87
+ expires_at: string
88
+ }
89
+
90
+ export interface NavigateResponse {
91
+ api_version: 'v1'
92
+ status: 'navigated'
93
+ session_id: string
94
+ final_url: string
95
+ title: string
96
+ readable_text: string
97
+ accessibility: AccessibilitySnapshot
98
+ navigated_at: string
99
+ }
100
+
101
+ export interface SnapshotResponse {
102
+ api_version: 'v1'
103
+ status: 'snapshot'
104
+ session_id: string
105
+ url: string
106
+ title: string
107
+ readable_text: string
108
+ accessibility: AccessibilitySnapshot
109
+ screenshot_base64: string
110
+ viewport: Viewport
111
+ sequence: number
112
+ captured_at: string
113
+ vision_steps_used: number
114
+ vision_steps_remaining: number
115
+ }
116
+
117
+ export interface InteractResponse {
118
+ api_version: 'v1'
119
+ status: 'interacted'
120
+ session_id: string
121
+ action: InteractionAction
122
+ sequence: number
123
+ interacted_at: string
124
+ }
125
+
126
+ export interface EndSessionResponse {
127
+ api_version: 'v1'
128
+ status: 'ended' | 'already_ended'
129
+ session_id: string
130
+ ended_at: string
131
+ }
132
+
133
+ export interface RequestOptions {
134
+ /** Abort the request early. Composed with the client timeout. */
135
+ signal?: AbortSignal
136
+ /** Override the client timeout for this call. Pass 0 to disable. */
137
+ timeoutMs?: number
138
+ }
139
+
140
+ export interface AgentBrowserOptions {
141
+ /** Defaults to `AGENT_BROWSER_URL`, then `http://127.0.0.1:8092`. */
142
+ baseUrl?: string
143
+ /** Required for create, navigate, interact, and end. Defaults to `AGENT_BROWSER_CONTROLLER_TOKEN`. */
144
+ controllerToken?: string
145
+ /** Sufficient for health and snapshot. Defaults to `AGENT_BROWSER_OBSERVER_TOKEN`. */
146
+ observerToken?: string
147
+ /** Per-request timeout in milliseconds. Defaults to 30000. Pass 0 to disable. */
148
+ timeoutMs?: number
149
+ /** Injectable transport, for tests or a custom agent. Defaults to global fetch. */
150
+ fetch?: typeof globalThis.fetch
151
+ /** Injectable environment, for tests. Defaults to `process.env`. */
152
+ env?: Record<string, string | undefined>
153
+ }
154
+
155
+ export declare class AgentBrowserError extends Error {
156
+ name: 'AgentBrowserError'
157
+ /** The server's stable error code, or undefined for a transport failure. */
158
+ code?: ErrorCode
159
+ httpStatus?: number
160
+ retryAfterSeconds?: number
161
+ readonly isCapacityReached: boolean
162
+ readonly isDestinationBlocked: boolean
163
+ constructor(
164
+ message: string,
165
+ options?: {
166
+ code?: ErrorCode
167
+ httpStatus?: number
168
+ retryAfterSeconds?: number
169
+ cause?: unknown
170
+ },
171
+ )
172
+ }
173
+
174
+ export declare class Session {
175
+ readonly id: string
176
+ readonly viewUrl: string
177
+ readonly createdAt: string
178
+ readonly expiresAt: string
179
+ readonly maxVisionSteps: number
180
+ ended: boolean
181
+
182
+ navigate(url: string, options?: RequestOptions): Promise<NavigateResponse>
183
+ snapshot(options?: RequestOptions): Promise<SnapshotResponse>
184
+ click(
185
+ target: { selector: string; x?: never; y?: never } | { x: number; y: number; selector?: never },
186
+ options?: RequestOptions,
187
+ ): Promise<InteractResponse>
188
+ type(
189
+ input:
190
+ | { text: string; selector: string; x?: never; y?: never }
191
+ | { text: string; x: number; y: number; selector?: never },
192
+ options?: RequestOptions,
193
+ ): Promise<InteractResponse>
194
+ press(key: AllowedKey, options?: RequestOptions): Promise<InteractResponse>
195
+ scroll(
196
+ input: { deltaX?: number; deltaY?: number; selector?: string; x?: number; y?: number },
197
+ options?: RequestOptions,
198
+ ): Promise<InteractResponse>
199
+ end(options?: RequestOptions): Promise<EndSessionResponse>
200
+ }
201
+
202
+ export declare class AgentBrowser {
203
+ constructor(options?: AgentBrowserOptions)
204
+ readonly baseUrl: string
205
+ health(options?: RequestOptions): Promise<HealthResponse>
206
+ createSession(
207
+ input?: { maxVisionSteps?: number },
208
+ options?: RequestOptions,
209
+ ): Promise<Session>
210
+ }
211
+
212
+ /**
213
+ * Run `fn` against a fresh session and always attempt to end it, including when `fn`
214
+ * throws. A failure to end never masks the original error.
215
+ */
216
+ export declare function withSession<T>(
217
+ browser: AgentBrowser,
218
+ fn: (session: Session) => Promise<T>,
219
+ input?: { maxVisionSteps?: number },
220
+ ): Promise<T>
221
+
222
+ export default AgentBrowser
package/src/index.js ADDED
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Client for the Agent Browser v1 API.
3
+ *
4
+ * The server exposes one closed JSON API. Every request and response carries
5
+ * `api_version: "v1"` and unknown fields are rejected, so this client sends
6
+ * exactly the documented fields and omits anything left undefined.
7
+ *
8
+ * @see https://github.com/AetherAI3/agent-browser/blob/main/docs/API.md
9
+ */
10
+
11
+ export const API_VERSION = 'v1'
12
+
13
+ export const DEFAULT_BASE_URL = 'http://127.0.0.1:8092'
14
+
15
+ /** Keys the server accepts for `press`. Anything else is refused server-side. */
16
+ export const ALLOWED_KEYS = Object.freeze([
17
+ 'Enter',
18
+ 'Escape',
19
+ 'Tab',
20
+ 'Backspace',
21
+ 'Delete',
22
+ 'Space',
23
+ 'ArrowUp',
24
+ 'ArrowDown',
25
+ 'ArrowLeft',
26
+ 'ArrowRight',
27
+ 'Home',
28
+ 'End',
29
+ 'PageUp',
30
+ 'PageDown',
31
+ 'Control+A',
32
+ 'Control+Z',
33
+ 'Control+Shift+Z',
34
+ 'Meta+A',
35
+ 'Meta+Z',
36
+ 'Meta+Shift+Z',
37
+ ])
38
+
39
+ /**
40
+ * An error returned by the Agent Browser API, or a transport failure reaching it.
41
+ *
42
+ * `code` is the server's stable error code when the response carried the documented
43
+ * error envelope, and `undefined` for transport-level failures.
44
+ */
45
+ export class AgentBrowserError extends Error {
46
+ /**
47
+ * @param {string} message
48
+ * @param {{ code?: string, httpStatus?: number, retryAfterSeconds?: number, cause?: unknown }} [options]
49
+ */
50
+ constructor(message, options = {}) {
51
+ super(message, options.cause === undefined ? undefined : { cause: options.cause })
52
+ this.name = 'AgentBrowserError'
53
+ this.code = options.code
54
+ this.httpStatus = options.httpStatus
55
+ this.retryAfterSeconds = options.retryAfterSeconds
56
+ }
57
+
58
+ /** True when the server refused because a session is already active. */
59
+ get isCapacityReached() {
60
+ return this.code === 'SESSION_CAPACITY_REACHED'
61
+ }
62
+
63
+ /** True when the server refused the destination rather than failing to reach it. */
64
+ get isDestinationBlocked() {
65
+ return this.code === 'DESTINATION_BLOCKED' || this.code === 'INVALID_URL'
66
+ }
67
+ }
68
+
69
+ /** Strip undefined values so the closed server models never see unknown or null keys. */
70
+ function compact(object) {
71
+ const out = {}
72
+ for (const [key, value] of Object.entries(object)) {
73
+ if (value !== undefined) out[key] = value
74
+ }
75
+ return out
76
+ }
77
+
78
+ function normalizeBaseUrl(value) {
79
+ return String(value).replace(/\/+$/, '')
80
+ }
81
+
82
+ /**
83
+ * A live session. Obtained from `AgentBrowser#createSession`; not constructed directly.
84
+ *
85
+ * Every method is a thin, typed call onto the documented routes. The session does not
86
+ * cache page state: `navigate` and `snapshot` each return the server's own bounded view.
87
+ */
88
+ export class Session {
89
+ /**
90
+ * @param {AgentBrowser} browser
91
+ * @param {import('./index.d.ts').CreateSessionResponse} created
92
+ */
93
+ constructor(browser, created) {
94
+ this.browser = browser
95
+ this.id = created.session_id
96
+ this.viewUrl = created.view_url
97
+ this.createdAt = created.created_at
98
+ this.expiresAt = created.expires_at
99
+ this.maxVisionSteps = created.max_vision_steps
100
+ this.ended = false
101
+ }
102
+
103
+ /** Navigate to an HTTP(S) URL. The server evaluates its egress policy separately from schema validation. */
104
+ navigate(url, options = {}) {
105
+ return this.browser._post('/browser/navigate', { session_id: this.id, url }, 'controller', options)
106
+ }
107
+
108
+ /** Capture bounded page state plus a base64 PNG. Consumes exactly one vision step. */
109
+ snapshot(options = {}) {
110
+ return this.browser._post('/browser/snapshot', { session_id: this.id }, 'observer', options)
111
+ }
112
+
113
+ /**
114
+ * Click a selector or an x/y point. Exactly one of the two is allowed by the server.
115
+ * @param {{ selector?: string, x?: number, y?: number }} target
116
+ */
117
+ click(target, options = {}) {
118
+ return this._interact({ action: 'click', target: compact(target) }, options)
119
+ }
120
+
121
+ /**
122
+ * Type text into a selector or an x/y point. Text is preserved byte for byte,
123
+ * including leading and trailing whitespace.
124
+ * @param {{ selector?: string, x?: number, y?: number, text: string }} input
125
+ */
126
+ type({ text, ...target }, options = {}) {
127
+ return this._interact({ action: 'type', target: compact(target), text }, options)
128
+ }
129
+
130
+ /**
131
+ * Press one of the allowed keys or combinations. Clipboard shortcuts are not allowlisted.
132
+ * @param {import('./index.d.ts').AllowedKey} key
133
+ */
134
+ press(key, options = {}) {
135
+ return this._interact({ action: 'press', key }, options)
136
+ }
137
+
138
+ /**
139
+ * Scroll by a bounded, nonzero delta.
140
+ * @param {{ deltaX?: number, deltaY?: number, selector?: string, x?: number, y?: number }} input
141
+ */
142
+ scroll({ deltaX, deltaY, ...target } = {}, options = {}) {
143
+ const body = { action: 'scroll', delta_x: deltaX, delta_y: deltaY }
144
+ const where = compact(target)
145
+ if (Object.keys(where).length > 0) body.target = where
146
+ return this._interact(body, options)
147
+ }
148
+
149
+ _interact(body, options) {
150
+ return this.browser._post(
151
+ '/browser/interact',
152
+ { session_id: this.id, ...compact(body) },
153
+ 'controller',
154
+ options,
155
+ )
156
+ }
157
+
158
+ /**
159
+ * End the session. Idempotent: a repeated call reports `already_ended` rather than
160
+ * resurrecting state, so calling this twice is safe.
161
+ */
162
+ async end(options = {}) {
163
+ const result = await this.browser._post(
164
+ '/browser/session/end',
165
+ { session_id: this.id },
166
+ 'controller',
167
+ options,
168
+ )
169
+ this.ended = true
170
+ return result
171
+ }
172
+ }
173
+
174
+ /**
175
+ * A client bound to one Agent Browser server.
176
+ *
177
+ * Observer and controller tokens are kept separate so the server's role split is visible
178
+ * in your own code: reads may be given only the observer token, while anything that
179
+ * creates, navigates, interacts, or ends requires the controller token.
180
+ */
181
+ export class AgentBrowser {
182
+ /**
183
+ * @param {import('./index.d.ts').AgentBrowserOptions} [options]
184
+ */
185
+ constructor(options = {}) {
186
+ const env = options.env ?? (typeof process !== 'undefined' ? process.env : {}) ?? {}
187
+ this.baseUrl = normalizeBaseUrl(options.baseUrl ?? env.AGENT_BROWSER_URL ?? DEFAULT_BASE_URL)
188
+ this.controllerToken = options.controllerToken ?? env.AGENT_BROWSER_CONTROLLER_TOKEN
189
+ this.observerToken = options.observerToken ?? env.AGENT_BROWSER_OBSERVER_TOKEN
190
+ this.timeoutMs = options.timeoutMs ?? 30_000
191
+ this._fetch = options.fetch ?? globalThis.fetch
192
+ if (typeof this._fetch !== 'function') {
193
+ throw new TypeError(
194
+ 'No fetch implementation available. Use Node 18 or newer, or pass options.fetch.',
195
+ )
196
+ }
197
+ }
198
+
199
+ /** Liveness and readiness. Accepts the observer token. */
200
+ health(options = {}) {
201
+ return this._request('GET', '/browser/health', undefined, 'observer', options)
202
+ }
203
+
204
+ /**
205
+ * Create the one owned session. A second concurrent create is refused with
206
+ * `SESSION_CAPACITY_REACHED` rather than queued.
207
+ * @param {{ maxVisionSteps?: number }} [input]
208
+ */
209
+ async createSession(input = {}, options = {}) {
210
+ const created = await this._post(
211
+ '/browser/session/create',
212
+ compact({ max_vision_steps: input.maxVisionSteps }),
213
+ 'controller',
214
+ options,
215
+ )
216
+ return new Session(this, created)
217
+ }
218
+
219
+ _post(path, body, role, options) {
220
+ return this._request('POST', path, body, role, options)
221
+ }
222
+
223
+ _tokenFor(role) {
224
+ if (role === 'observer') return this.observerToken ?? this.controllerToken
225
+ return this.controllerToken ?? this.observerToken
226
+ }
227
+
228
+ async _request(method, path, body, role, options = {}) {
229
+ const headers = { accept: 'application/json' }
230
+ const token = this._tokenFor(role)
231
+ if (token) headers.authorization = `Bearer ${token}`
232
+
233
+ let payload
234
+ if (body !== undefined) {
235
+ headers['content-type'] = 'application/json'
236
+ payload = JSON.stringify({ api_version: API_VERSION, ...body })
237
+ }
238
+
239
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs
240
+ const controller = new AbortController()
241
+ const onAbort = () => controller.abort(options.signal?.reason)
242
+ if (options.signal) {
243
+ if (options.signal.aborted) onAbort()
244
+ else options.signal.addEventListener('abort', onAbort, { once: true })
245
+ }
246
+ const timer =
247
+ timeoutMs > 0
248
+ ? setTimeout(
249
+ () => controller.abort(new Error(`Agent Browser request timed out after ${timeoutMs}ms`)),
250
+ timeoutMs,
251
+ )
252
+ : undefined
253
+
254
+ let response
255
+ try {
256
+ response = await this._fetch(`${this.baseUrl}${path}`, {
257
+ method,
258
+ headers,
259
+ body: payload,
260
+ signal: controller.signal,
261
+ })
262
+ } catch (cause) {
263
+ throw new AgentBrowserError(
264
+ `Could not reach Agent Browser at ${this.baseUrl}: ${cause?.message ?? cause}`,
265
+ { cause },
266
+ )
267
+ } finally {
268
+ if (timer !== undefined) clearTimeout(timer)
269
+ options.signal?.removeEventListener?.('abort', onAbort)
270
+ }
271
+
272
+ const text = await response.text()
273
+ let parsed
274
+ try {
275
+ parsed = text ? JSON.parse(text) : undefined
276
+ } catch {
277
+ parsed = undefined
278
+ }
279
+
280
+ if (!response.ok) {
281
+ const detail = parsed?.error
282
+ const retryAfter = Number(response.headers?.get?.('retry-after'))
283
+ throw new AgentBrowserError(detail?.message ?? `Agent Browser returned HTTP ${response.status}`, {
284
+ code: detail?.code,
285
+ httpStatus: response.status,
286
+ retryAfterSeconds: Number.isFinite(retryAfter) ? retryAfter : undefined,
287
+ })
288
+ }
289
+
290
+ return parsed
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Run `fn` against a fresh session and always attempt to end it, including when `fn`
296
+ * throws. A failure to end never masks the original error.
297
+ *
298
+ * @template T
299
+ * @param {AgentBrowser} browser
300
+ * @param {(session: Session) => Promise<T>} fn
301
+ * @returns {Promise<T>}
302
+ */
303
+ export async function withSession(browser, fn, input = {}) {
304
+ const session = await browser.createSession(input)
305
+ try {
306
+ return await fn(session)
307
+ } finally {
308
+ try {
309
+ await session.end()
310
+ } catch {
311
+ // The caller's outcome is what matters; a cleanup failure must not replace it.
312
+ }
313
+ }
314
+ }
315
+
316
+ export default AgentBrowser