@rezkam/browser-tools 1.0.2 → 1.0.4
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/CHANGELOG.md +57 -0
- package/LICENSE +202 -0
- package/README.md +62 -53
- package/package.json +11 -4
- package/scripts/browser-control.mjs +140 -23
- package/scripts/stop.mjs +3 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# @rezkam/browser-tools
|
|
2
|
+
|
|
3
|
+
## 1.0.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 2ef608b: Automatically reclaim managed Chrome sessions that have run for two hours after their recorded launcher exits. Record immutable launcher process identity to detect PID reuse, keep live launchers protected regardless of age, and run the fail-safe reap before enforcing the browser limit.
|
|
8
|
+
- e453b80: Skip local ports occupied by non-CDP processes during automatic managed Chrome allocation, and verify that the process responding after launch is the managed Chrome that was started.
|
|
9
|
+
|
|
10
|
+
## 1.0.3
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- 87a6ab3: Point the package at its own standalone repository. `repository.url` is now `git+https://github.com/rezkam/browser-tools.git` with no monorepo `directory`, and `homepage` and `bugs` resolve there too, so npm's repository, homepage, and issue links no longer send consumers to a path that does not hold this package. The skill install command and documentation links now target the same repository, which is the source of both the skill and the package.
|
|
15
|
+
|
|
16
|
+
## 1.0.2
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- 197694d: Clean up managed Chrome lifecycle records and profile clones when Chrome exits between the final SIGTERM wait and the SIGKILL safety recheck.
|
|
21
|
+
|
|
22
|
+
## 1.0.1
|
|
23
|
+
|
|
24
|
+
### Patch Changes
|
|
25
|
+
|
|
26
|
+
- 07332c7: Preserve managed-browser lifecycle records and profile clones when Chrome shutdown fails, recognize exited child-process zombies, fail closed when clone ownership cannot be inventoried, return a failing CLI status when Chrome remains alive, and keep headless Chrome launches out of macOS Dock recents.
|
|
27
|
+
|
|
28
|
+
## 1.0.0
|
|
29
|
+
|
|
30
|
+
### Major Changes
|
|
31
|
+
|
|
32
|
+
- 6a7d46c: Require an owner for every managed browser, and make an unowned one reclaimable. `startChrome` now refuses to launch without an `ownerId`: an unowned browser cannot be adopted or stopped by anything, because its owner token exists only in the caller that started it, so once that process exits the browser holds a slot, its clone directory, and its memory with nothing able to reclaim it. This is the breaking part, since library callers that omitted `ownerId` now fail fast instead of leaking. A command-line `browser-tools start` stamps `cli` when neither `--owner-id` nor `BROWSER_TOOLS_OWNER_ID` is set, so a shell launch is never anonymous, and each lifecycle record now stores `launchedByPid` so a browser that outlives its launcher stays attributable.
|
|
33
|
+
|
|
34
|
+
Cleanup no longer has a blind spot. A browser that nothing owns counts as reclaimable even when its lifecycle files are perfectly consistent, so `stop --reap`, `stop --prune`, and the automatic pre-launch reap can now clear it. `stop --port <n>` may also stop an unowned browser without a token and reports `(reclaimed: nothing owned it)` when it does. Owned browsers still require their matching token, and adopting or connecting never accepts an unowned browser, so this cannot be used to hijack one.
|
|
35
|
+
|
|
36
|
+
### Minor Changes
|
|
37
|
+
|
|
38
|
+
- 9858593: Bound the number of concurrent managed Chrome browsers and recover leaked ones. Starting without `--port` now reuses a browser the caller's owner token already owns instead of allocating another port, a hard cap (default 5, override with `BROWSER_TOOLS_MAX_BROWSERS` or `browser.maxBrowsers`) refuses a launch that would exceed it, and start warns on the last free slot and about browsers running longer than two hours. The live count is read from the process table rather than lifecycle files, so browsers stay visible even when their state files are gone. New `browser-tools stop --status`, `--reap`, and `--reap --dry-run` list and sweep managed browsers no lifecycle file tracks; `--prune` reaps before pruning clones, and start reaps automatically so a leak self-heals. Stop no longer deletes lifecycle files for a process that is still running, which previously turned a safety mismatch into a permanently unaddressable browser.
|
|
39
|
+
|
|
40
|
+
## 0.3.0
|
|
41
|
+
|
|
42
|
+
### Minor Changes
|
|
43
|
+
|
|
44
|
+
- f7f8067: Capture owner-protected filtered HTTP HAR and raw CDP events from active-tab interactions, extract private chronological network recipes for agent analysis, and send guarded direct CDP calls. Preserve exact debugging evidence by default with optional redaction, and use raw CDP for WebSocket protocol traffic.
|
|
45
|
+
- e9e9c3c: Record owner-protected active-tab GIFs around multi-step browser interactions, require pre-action and post-action frames and meaningful output filenames, then probe recordings and generate owner-only sampled contact sheets for visual review.
|
|
46
|
+
|
|
47
|
+
## 0.2.1
|
|
48
|
+
|
|
49
|
+
### Patch Changes
|
|
50
|
+
|
|
51
|
+
- 8ea5041: Verify automated npm publishing after the initial package release.
|
|
52
|
+
|
|
53
|
+
## 0.2.0
|
|
54
|
+
|
|
55
|
+
### Minor Changes
|
|
56
|
+
|
|
57
|
+
- 85e2099: Publish Browser Tools as an installable npm package, `@rezkam/browser-tools`, with a `browser-tools` CLI (`start`, `status`, `stop`, `nav`, `eval`, `screenshot`, `pick`, `config`, `scrape-page`, `extract-article`) and a programmatic export of the browser control module, so external consumers can depend on a pinned version instead of a cloned script path. The skill's existing `scripts/*.mjs` interface for agents working directly in this repo is unchanged.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,96 +1,105 @@
|
|
|
1
1
|
# @rezkam/browser-tools
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Managed Chrome automation with isolated profiles and owner-protected sessions. Browser Tools can drive pages, inspect the DOM, capture visual and network evidence, and extract page content without connecting to or stopping your main Chrome.
|
|
4
4
|
|
|
5
|
-
This
|
|
5
|
+
This repository provides both the `browser-tools` skill and the `@rezkam/browser-tools` npm package. The skill uses the same CLI that the package installs.
|
|
6
6
|
|
|
7
|
-
##
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Isolated browser sessions:** launch windowed or headless Chrome with a fresh profile or a copied Chrome profile, including existing site sessions and extensions.
|
|
10
|
+
- **Safe lifecycle management:** every managed browser has an owner token. Browser Tools verifies process identity before connecting or stopping, limits concurrent browsers, and automatically reclaims old sessions after their recorded launcher exits.
|
|
11
|
+
- **Page control and inspection:** navigate tabs, evaluate asynchronous JavaScript, take viewport or full-page screenshots, and interactively pick single or multiple DOM elements.
|
|
12
|
+
- **Page extraction:** collect article-like links and nearby timestamps, or extract readable article text from the active tab.
|
|
13
|
+
- **Visual evidence:** record an active-tab interaction as a GIF, then generate a sampled contact sheet and JSON metadata for review.
|
|
14
|
+
- **Network and protocol tooling:** capture filtered HAR 1.2 traffic, extract a chronological request recipe, record selected raw CDP events, and send guarded CDP calls to the active tab.
|
|
15
|
+
- **Local profile configuration:** discover Chrome profiles, create private aliases, and associate one or more profiles with a task.
|
|
8
16
|
|
|
9
|
-
|
|
17
|
+
## Install
|
|
10
18
|
|
|
11
|
-
|
|
19
|
+
Install the skill when Browser Tools should be discoverable as an automation skill:
|
|
12
20
|
|
|
13
21
|
```bash
|
|
14
|
-
npx skills add rezkam/
|
|
22
|
+
npx skills add rezkam/browser-tools
|
|
15
23
|
```
|
|
16
24
|
|
|
17
|
-
|
|
25
|
+
Install the package for the global CLI and programmatic exports:
|
|
18
26
|
|
|
19
27
|
```bash
|
|
20
28
|
npm install -g @rezkam/browser-tools
|
|
21
29
|
```
|
|
22
30
|
|
|
23
|
-
|
|
31
|
+
Commands can also run without a global install:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
npx @rezkam/browser-tools <command>
|
|
35
|
+
```
|
|
24
36
|
|
|
25
|
-
GIF recording and review
|
|
37
|
+
Browser Tools requires macOS, Google Chrome, and Node.js 20 or newer. GIF recording and review additionally require `ffmpeg` and `ffprobe`:
|
|
26
38
|
|
|
27
39
|
```bash
|
|
28
40
|
brew install ffmpeg
|
|
29
41
|
```
|
|
30
42
|
|
|
31
|
-
##
|
|
32
|
-
|
|
33
|
-
Each subcommand dispatches to the matching script unchanged; flags are the same as the underlying script.
|
|
43
|
+
## Quick start
|
|
34
44
|
|
|
35
45
|
```bash
|
|
36
|
-
browser-tools start --
|
|
46
|
+
browser-tools start --headless
|
|
37
47
|
export BROWSER_TOOLS_OWNER_TOKEN="<owner token from start output>"
|
|
38
|
-
|
|
48
|
+
|
|
39
49
|
browser-tools nav https://example.com --port <reported port>
|
|
40
50
|
browser-tools eval 'document.title' --port <reported port>
|
|
41
51
|
browser-tools screenshot --full --port <reported port>
|
|
42
|
-
|
|
43
|
-
# Perform the multi-step interaction.
|
|
44
|
-
browser-tools record-gif stop --port <reported port>
|
|
45
|
-
browser-tools review-gif "$PWD/login_process.gif"
|
|
46
|
-
browser-tools record-har start --output "$PWD/checkout_api_network.har" --preset api --port <reported port>
|
|
47
|
-
# Perform the browser interaction, then stop and extract a non-executable recipe.
|
|
48
|
-
browser-tools record-har stop --port <reported port>
|
|
49
|
-
browser-tools extract-har "$PWD/checkout_api_network.har"
|
|
50
|
-
browser-tools record-cdp start --output "$PWD/checkout_network_events.jsonl" --domain Network --event 'Network.*' --port <reported port>
|
|
51
|
-
browser-tools record-cdp stop --port <reported port>
|
|
52
|
-
browser-tools cdp call Runtime.evaluate --params '{"expression":"document.title"}' --port <reported port>
|
|
53
|
-
browser-tools pick "Click the price" --port <reported port>
|
|
54
|
-
browser-tools scrape-page --port <reported port>
|
|
55
|
-
browser-tools extract-article --chars 6000 --port <reported port>
|
|
52
|
+
|
|
56
53
|
browser-tools stop --clean --port <reported port>
|
|
57
|
-
browser-tools config task-profile set <task> --profile "<alias>"
|
|
58
54
|
```
|
|
59
55
|
|
|
60
|
-
|
|
56
|
+
Use `--profile "<profile or alias>"` when an existing login is needed, `--sync` to refresh the copied profile, or `--task <task>` to use configured task profiles.
|
|
61
57
|
|
|
62
|
-
##
|
|
58
|
+
## CLI capabilities
|
|
63
59
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
60
|
+
| Area | Commands | What they do |
|
|
61
|
+
| --- | --- | --- |
|
|
62
|
+
| Browser lifecycle | `start`, `status`, `stop` | Launch, inspect, stop, clean, reap, and prune managed Chrome sessions |
|
|
63
|
+
| Profile configuration | `config` | Discover profiles, list active profiles, and manage task-to-profile mappings |
|
|
64
|
+
| Page control | `nav`, `eval`, `screenshot` | Navigate the active tab or a new background tab, run page JavaScript, and capture PNG screenshots |
|
|
65
|
+
| DOM inspection | `pick` | Select one or more visible elements and return tag, id, class, text, HTML, and parent information |
|
|
66
|
+
| Page extraction | `scrape-page`, `extract-article` | Extract article-like links with timestamps or readable article text from the active tab |
|
|
67
|
+
| Visual recording | `record-gif`, `review-gif` | Record an interaction with pre-roll and post-roll frames, then create a contact sheet and metadata report |
|
|
68
|
+
| HTTP capture | `record-har`, `extract-har` | Capture filtered active-tab traffic and derive a compact, non-executable request recipe |
|
|
69
|
+
| Chrome DevTools Protocol | `record-cdp`, `cdp` | Record selected raw protocol events or send one guarded direct method call |
|
|
67
70
|
|
|
68
|
-
|
|
71
|
+
Run `browser-tools --help` for the command list. Commands with detailed option references, such as `record-har`, `record-cdp`, and `review-gif`, also support command-level `--help`.
|
|
69
72
|
|
|
70
|
-
##
|
|
73
|
+
## Safety model
|
|
71
74
|
|
|
72
|
-
-
|
|
73
|
-
-
|
|
74
|
-
-
|
|
75
|
-
-
|
|
76
|
-
-
|
|
77
|
-
-
|
|
78
|
-
- `
|
|
79
|
-
- HAR, recipes, raw CDP events, and direct results preserve exact debugging evidence by default. Add `--redact` to filter sensitive-looking values. Capture files are owner-only `0600`, not encrypted.
|
|
80
|
-
- Config, cache, and artifact directories default to `~/.agents/browser-tools/config.json`, `~/.cache/pi-browser-tools`, and `/tmp`, overridable via `BROWSER_TOOLS_CONFIG_DIR`, `BROWSER_TOOLS_CACHE_DIR`, `BROWSER_TOOLS_ARTIFACT_DIR`, `BROWSER_TOOLS_CHROME_SOURCE_DIR`, and `BROWSER_TOOLS_CHROME_BIN`.
|
|
81
|
-
- Requires macOS Chrome and Node.js 20+. GIF recording and review require ffmpeg and ffprobe.
|
|
75
|
+
- Managed Chrome always uses a separate user data directory. Copied profiles are snapshots and never run against the live Chrome profile.
|
|
76
|
+
- Commands that connect to Chrome or stop an owned browser require the owner token printed by `start`. The token protects browser control, recordings, network capture, CDP access, and shutdown.
|
|
77
|
+
- Google identity data is removed from copied profiles by default to protect the source session. `--include-google` is an explicit opt-in for Google-backed workflows.
|
|
78
|
+
- Starting without an explicit port can reuse a browser already owned by the caller or allocate another available port. The default concurrent browser limit is five.
|
|
79
|
+
- A managed browser older than two hours becomes reclaimable after its recorded launcher exits. The next start reaps it before enforcing the concurrency limit, while browsers with live launchers remain protected regardless of age.
|
|
80
|
+
- HAR files, extracted recipes, raw CDP events, and GIF review artifacts are written as private local files. Network and protocol output preserves exact evidence by default, with `--redact` available when sensitive values are not needed.
|
|
81
|
+
- `extract-har` only describes captured requests. It does not execute or replay them. Known direct CDP methods that bypass managed-browser lifecycle controls are blocked.
|
|
82
82
|
|
|
83
|
-
|
|
83
|
+
Browser Tools stores local configuration under `~/.agents/browser-tools` and managed profiles under `~/.cache/pi-browser-tools`. Timestamped artifacts such as screenshots default to the system temporary directory, while derived outputs such as HAR recipes and GIF reviews stay beside their input files. The documented `BROWSER_TOOLS_*` environment variables override configurable locations.
|
|
84
84
|
|
|
85
|
-
|
|
85
|
+
For detailed ownership rules, profile behavior, capture filters, and command options, see the repository's [SKILL.md](https://github.com/rezkam/browser-tools/blob/main/SKILL.md) and [Browser Control reference](https://github.com/rezkam/browser-tools/blob/main/references/browser-control.md).
|
|
86
86
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
87
|
+
## Programmatic use
|
|
88
|
+
|
|
89
|
+
```js
|
|
90
|
+
import { activePage, connectBrowser, startChrome, stopChrome, withBrowser } from '@rezkam/browser-tools';
|
|
91
|
+
import { runBrowserResource } from '@rezkam/browser-tools/resource-helper.mjs';
|
|
91
92
|
```
|
|
92
93
|
|
|
93
|
-
The
|
|
94
|
+
The root package export and `@rezkam/browser-tools/browser-control.mjs` both expose the browser lifecycle and connection module. The resource helper export provides the shared lifecycle for generic extractors.
|
|
95
|
+
|
|
96
|
+
## Development
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
npm test # Unit and CLI contract tests
|
|
100
|
+
npm run test:e2e # Real Chrome and ffmpeg integration tests
|
|
101
|
+
npm run validate # Full validation suite
|
|
102
|
+
```
|
|
94
103
|
|
|
95
104
|
## License
|
|
96
105
|
|
package/package.json
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rezkam/browser-tools",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.4",
|
|
4
4
|
"description": "Sandboxed, owner-token-protected Chrome automation for AI agents: control pages, record and review GIFs, capture HAR and raw CDP events, send CDP calls, and manage Chrome profiles.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
9
|
-
"url": "git+https://github.com/rezkam/
|
|
10
|
-
|
|
9
|
+
"url": "git+https://github.com/rezkam/browser-tools.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/rezkam/browser-tools#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/rezkam/browser-tools/issues"
|
|
11
14
|
},
|
|
12
15
|
"engines": {
|
|
13
16
|
"node": ">=20"
|
|
@@ -24,7 +27,8 @@
|
|
|
24
27
|
"files": [
|
|
25
28
|
"bin",
|
|
26
29
|
"scripts",
|
|
27
|
-
"README.md"
|
|
30
|
+
"README.md",
|
|
31
|
+
"CHANGELOG.md"
|
|
28
32
|
],
|
|
29
33
|
"publishConfig": {
|
|
30
34
|
"access": "public",
|
|
@@ -38,5 +42,8 @@
|
|
|
38
42
|
},
|
|
39
43
|
"dependencies": {
|
|
40
44
|
"puppeteer-core": "^24.42.0"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@changesets/cli": "^2.31.0"
|
|
41
48
|
}
|
|
42
49
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
2
|
import { spawn, spawnSync } from 'node:child_process';
|
|
3
|
+
import { createConnection } from 'node:net';
|
|
3
4
|
import {
|
|
4
5
|
accessSync,
|
|
5
6
|
chmodSync,
|
|
@@ -19,6 +20,7 @@ import puppeteer from 'puppeteer-core';
|
|
|
19
20
|
|
|
20
21
|
export const DEFAULT_PORT = 9222;
|
|
21
22
|
export const CONNECT_PROBE_TIMEOUT_MS = 3000;
|
|
23
|
+
export const PORT_OCCUPANCY_PROBE_TIMEOUT_MS = 250;
|
|
22
24
|
export const CHROME_READY_TIMEOUT_MS = 15000;
|
|
23
25
|
export const CHROME_READY_PROBE_TIMEOUT_MS = 250;
|
|
24
26
|
export const DEFAULT_CHROME_BIN = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
|
|
@@ -49,7 +51,7 @@ export const MAX_BROWSERS_ENV = 'BROWSER_TOOLS_MAX_BROWSERS';
|
|
|
49
51
|
// A managed browser older than this is almost certainly a leftover from a finished agent session.
|
|
50
52
|
export const STALE_BROWSER_AGE_MS = 2 * 60 * 60 * 1000;
|
|
51
53
|
export const PENDING_BROWSER_STATE_MAX_AGE_MS = 5000;
|
|
52
|
-
export const REAP_HINT = 'Run scripts/stop.mjs --reap to sweep managed browsers
|
|
54
|
+
export const REAP_HINT = 'Run scripts/stop.mjs --reap to sweep reclaimable managed browsers whose lifecycle tracking or launcher lease has expired.';
|
|
53
55
|
|
|
54
56
|
export function agentConfigRoot() {
|
|
55
57
|
return process.env.AGENT_CONFIG_DIR || join(homedir(), '.agents');
|
|
@@ -388,18 +390,73 @@ export async function browserWSEndpoint(port = DEFAULT_PORT, timeoutMs = CONNECT
|
|
|
388
390
|
}
|
|
389
391
|
}
|
|
390
392
|
|
|
391
|
-
|
|
393
|
+
/**
|
|
394
|
+
* Detect any local listener, not just a responsive CDP endpoint. A normal Chrome
|
|
395
|
+
* can occupy the preferred debugging port without exposing a usable
|
|
396
|
+
* /json/version response, and launching against that port otherwise fails only
|
|
397
|
+
* after the full readiness timeout. Unexpected probe errors are treated as
|
|
398
|
+
* occupied so an uncertain port is never handed to Chrome.
|
|
399
|
+
*/
|
|
400
|
+
function tcpListenerOnHost(port, host, timeoutMs) {
|
|
401
|
+
return new Promise((resolvePromise) => {
|
|
402
|
+
const socket = createConnection({ host, port });
|
|
403
|
+
let settled = false;
|
|
404
|
+
const finish = (occupied) => {
|
|
405
|
+
if (settled) return;
|
|
406
|
+
settled = true;
|
|
407
|
+
socket.destroy();
|
|
408
|
+
resolvePromise(occupied);
|
|
409
|
+
};
|
|
410
|
+
socket.once('connect', () => finish(true));
|
|
411
|
+
socket.once('error', (error) => {
|
|
412
|
+
const code = error && typeof error === 'object' ? error.code : undefined;
|
|
413
|
+
finish(!['ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'EADDRNOTAVAIL', 'EAFNOSUPPORT', 'EPROTONOSUPPORT', 'ENOTSUP'].includes(code));
|
|
414
|
+
});
|
|
415
|
+
socket.setTimeout(timeoutMs, () => finish(true));
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
export async function isPortOccupied(port = DEFAULT_PORT, timeoutMs = PORT_OCCUPANCY_PROBE_TIMEOUT_MS) {
|
|
420
|
+
const normalizedPort = normalizePort(port);
|
|
421
|
+
const [ipv4, ipv6] = await Promise.all([
|
|
422
|
+
tcpListenerOnHost(normalizedPort, '127.0.0.1', timeoutMs),
|
|
423
|
+
tcpListenerOnHost(normalizedPort, '::1', timeoutMs),
|
|
424
|
+
]);
|
|
425
|
+
return ipv4 || ipv6;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
export function devToolsActivePortMatches(userDataDir, endpoint) {
|
|
429
|
+
if (!userDataDir || !endpoint) return false;
|
|
430
|
+
try {
|
|
431
|
+
const url = new URL(endpoint);
|
|
432
|
+
const activePortFile = readFileSync(join(userDataDir, 'DevToolsActivePort'), 'utf8').trim().split(/\r?\n/);
|
|
433
|
+
const endpointPort = url.port || (url.protocol === 'ws:' ? '80' : url.protocol === 'wss:' ? '443' : '');
|
|
434
|
+
return activePortFile[0] === endpointPort && activePortFile[1] === url.pathname;
|
|
435
|
+
} catch {
|
|
436
|
+
return false;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export async function waitForChromeEndpoint(
|
|
392
441
|
port = DEFAULT_PORT,
|
|
393
442
|
{ timeoutMs = CHROME_READY_TIMEOUT_MS, intervalMs = 250, probeTimeoutMs = CHROME_READY_PROBE_TIMEOUT_MS } = {},
|
|
394
443
|
) {
|
|
395
444
|
const deadline = Date.now() + timeoutMs;
|
|
396
445
|
while (Date.now() < deadline) {
|
|
397
446
|
const remainingMs = Math.max(1, deadline - Date.now());
|
|
398
|
-
|
|
447
|
+
const endpoint = await browserWSEndpoint(port, Math.min(probeTimeoutMs, remainingMs));
|
|
448
|
+
if (endpoint) return endpoint;
|
|
399
449
|
const sleepMs = Math.min(intervalMs, Math.max(0, deadline - Date.now()));
|
|
400
450
|
if (sleepMs > 0) await sleep(sleepMs);
|
|
401
451
|
}
|
|
402
|
-
return
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
export async function waitForChromeReady(
|
|
456
|
+
port = DEFAULT_PORT,
|
|
457
|
+
options = {},
|
|
458
|
+
) {
|
|
459
|
+
return Boolean(await waitForChromeEndpoint(port, options));
|
|
403
460
|
}
|
|
404
461
|
|
|
405
462
|
export function profileCopyReady(profileName, profileDataDir = profileDataDirForPort()) {
|
|
@@ -1212,6 +1269,21 @@ export function staleManagedBrowsers(processes = listManagedChromeProcesses(), {
|
|
|
1212
1269
|
return processes.filter((entry) => Number.isFinite(entry.ageMs) && entry.ageMs >= maxAgeMs);
|
|
1213
1270
|
}
|
|
1214
1271
|
|
|
1272
|
+
function managedBrowserLauncherIsActive(state) {
|
|
1273
|
+
const launcherPid = Number(state?.launchedByPid);
|
|
1274
|
+
if (!Number.isInteger(launcherPid) || launcherPid < 1) return false;
|
|
1275
|
+
const recordedIdentity = typeof state?.launchedByProcessStartIdentity === 'string'
|
|
1276
|
+
? state.launchedByProcessStartIdentity
|
|
1277
|
+
: null;
|
|
1278
|
+
if (!recordedIdentity) return processExists(launcherPid);
|
|
1279
|
+
|
|
1280
|
+
const currentIdentity = processStartIdentity(launcherPid);
|
|
1281
|
+
if (currentIdentity) return currentIdentity === recordedIdentity;
|
|
1282
|
+
// A transient process-table read failure must fail closed. Only consider the launcher gone when
|
|
1283
|
+
// the independent process existence check agrees that the PID no longer exists.
|
|
1284
|
+
return processExists(launcherPid);
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1215
1287
|
function readManagedPid(pidFile) {
|
|
1216
1288
|
try {
|
|
1217
1289
|
const pid = Number.parseInt(readFileSync(pidFile, 'utf-8').trim(), 10);
|
|
@@ -1221,8 +1293,8 @@ function readManagedPid(pidFile) {
|
|
|
1221
1293
|
}
|
|
1222
1294
|
}
|
|
1223
1295
|
|
|
1224
|
-
//
|
|
1225
|
-
//
|
|
1296
|
+
// Managed browsers the reaper may safely reclaim. This includes browsers whose lifecycle files no
|
|
1297
|
+
// longer describe them, unowned browsers, and old browsers whose recorded launcher has exited.
|
|
1226
1298
|
export function orphanedManagedBrowsers(processes = listManagedChromeProcesses()) {
|
|
1227
1299
|
return processes.filter((entry) => {
|
|
1228
1300
|
// A concurrent start holds the port lock from before the spawn until the readiness probe passes,
|
|
@@ -1245,6 +1317,13 @@ export function orphanedManagedBrowsers(processes = listManagedChromeProcesses()
|
|
|
1245
1317
|
// An unowned browser is tracked but unreachable: its owner token lives only in the caller that
|
|
1246
1318
|
// started it, so once that process exits nothing can adopt or stop it. Reclaim it as garbage.
|
|
1247
1319
|
if (!normalizeOwnerValue(state.ownerId)) return true;
|
|
1320
|
+
// Ownership cannot make a leaked browser immortal. Once the browser is old enough to be stale
|
|
1321
|
+
// and the process that launched it is gone, no live owner process remains to close it.
|
|
1322
|
+
if (
|
|
1323
|
+
Number.isFinite(entry.ageMs) &&
|
|
1324
|
+
entry.ageMs >= STALE_BROWSER_AGE_MS &&
|
|
1325
|
+
!managedBrowserLauncherIsActive(state)
|
|
1326
|
+
) return true;
|
|
1248
1327
|
return false;
|
|
1249
1328
|
});
|
|
1250
1329
|
}
|
|
@@ -1253,9 +1332,9 @@ export function forcedKillStatus(exited) {
|
|
|
1253
1332
|
return exited ? 'killed' : 'failed';
|
|
1254
1333
|
}
|
|
1255
1334
|
|
|
1256
|
-
// Kill managed browsers
|
|
1257
|
-
//
|
|
1258
|
-
//
|
|
1335
|
+
// Kill reclaimable managed browsers. Safe by construction: every target came from
|
|
1336
|
+
// parseManagedChromeProcesses, so it carries our managed token and a user-data-dir inside our cache
|
|
1337
|
+
// dir. Old tracked browsers are eligible only after their launcher exits and the grace period ends.
|
|
1259
1338
|
export function reapOrphanedChromes({ dryRun = false, processes = listManagedChromeProcesses() } = {}) {
|
|
1260
1339
|
const orphans = orphanedManagedBrowsers(processes);
|
|
1261
1340
|
const reaped = [];
|
|
@@ -1312,7 +1391,7 @@ function describeBrowserInventory(processes, { limit = 10, staleMaxAgeMs = STALE
|
|
|
1312
1391
|
const lines = processes.slice(0, limit).map((entry) => {
|
|
1313
1392
|
const stale = Number.isFinite(entry.ageMs) && entry.ageMs >= staleMaxAgeMs;
|
|
1314
1393
|
const pid = Number.isInteger(Number(entry.pid)) ? `PID ${entry.pid}` : 'PID unknown';
|
|
1315
|
-
return ` :${entry.port} ${pid} up ${formatBrowserAge(entry.ageMs)}${stale ? ' <-
|
|
1394
|
+
return ` :${entry.port} ${pid} up ${formatBrowserAge(entry.ageMs)}${stale ? ' <- running over 2h, likely a leftover' : ''}`;
|
|
1316
1395
|
});
|
|
1317
1396
|
if (processes.length > limit) lines.push(` ... and ${processes.length - limit} more`);
|
|
1318
1397
|
return lines.join('\n');
|
|
@@ -1335,7 +1414,7 @@ export function assertManagedBrowserCapacity({ processes = listManagedChromeProc
|
|
|
1335
1414
|
staleLine +
|
|
1336
1415
|
`\n To continue, do one of these:\n` +
|
|
1337
1416
|
` scripts/stop.mjs --status see this list again at any time\n` +
|
|
1338
|
-
` scripts/stop.mjs --reap --dry-run preview
|
|
1417
|
+
` scripts/stop.mjs --reap --dry-run preview reclaimable leaked browsers\n` +
|
|
1339
1418
|
` scripts/stop.mjs --prune reap those, then drop their unused clones\n` +
|
|
1340
1419
|
` scripts/stop.mjs --port <n> --owner-token "$${OWNER_TOKEN_ENV}" stop one you own\n\n` +
|
|
1341
1420
|
` Best fix if these are yours: export ${OWNER_TOKEN_ENV} from the first start, and later\n` +
|
|
@@ -1366,7 +1445,8 @@ export function managedBrowserStartupWarnings({
|
|
|
1366
1445
|
`${stale.length} managed browser${stale.length === 1 ? '' : 's'} ${stale.length === 1 ? 'has' : 'have'} been running over ${hours}h ` +
|
|
1367
1446
|
`(${describePorts(stale)}), likely left over from a finished session. ` +
|
|
1368
1447
|
`Stop a tracked browser with scripts/stop.mjs --port <n> --owner-token "$${OWNER_TOKEN_ENV}". ` +
|
|
1369
|
-
`
|
|
1448
|
+
`Old sessions whose launcher has exited are reclaimed automatically by the next start. ` +
|
|
1449
|
+
`Use scripts/stop.mjs --reap --dry-run to preview all reclaimable sessions.`,
|
|
1370
1450
|
);
|
|
1371
1451
|
}
|
|
1372
1452
|
return warnings;
|
|
@@ -1496,6 +1576,8 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
|
|
|
1496
1576
|
const chromeBin = browserToolsChromeBin();
|
|
1497
1577
|
const userAgent = headless ? headlessUserAgent(chromeBin) : null;
|
|
1498
1578
|
const args = chromeLaunchArgs({ port: normalizedPort, profileName, managedToken, userDataDir: launchUserDataDir, headless, userAgent });
|
|
1579
|
+
// A stale marker must not make a later launch appear to own a competing endpoint.
|
|
1580
|
+
rmSync(join(launchUserDataDir, 'DevToolsActivePort'), { force: true });
|
|
1499
1581
|
assertChromeBinaryLaunchable(chromeBin);
|
|
1500
1582
|
const pidFile = pidFileForPort(normalizedPort);
|
|
1501
1583
|
const stateFile = stateFileForPort(normalizedPort);
|
|
@@ -1528,6 +1610,9 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
|
|
|
1528
1610
|
...buildOwnerState({ ownerToken: effectiveOwnerToken, ownerId }),
|
|
1529
1611
|
// Who launched this browser, so a leaked one is attributable instead of anonymous.
|
|
1530
1612
|
launchedByPid: process.pid,
|
|
1613
|
+
// The PID can be reused after the launcher exits. Record its start identity so a different
|
|
1614
|
+
// process inheriting the same number cannot keep an expired browser lease alive.
|
|
1615
|
+
launchedByProcessStartIdentity: processStartIdentity(process.pid),
|
|
1531
1616
|
args,
|
|
1532
1617
|
startedAt: new Date().toISOString(),
|
|
1533
1618
|
}, null, 2));
|
|
@@ -1544,6 +1629,7 @@ export async function findAvailablePort(startPort = DEFAULT_PORT, { maxAttempts
|
|
|
1544
1629
|
cleanupStaleManagedStateForPort(port);
|
|
1545
1630
|
if (
|
|
1546
1631
|
!(await browserWSEndpoint(port)) &&
|
|
1632
|
+
!(await isPortOccupied(port)) &&
|
|
1547
1633
|
!existsSync(stateFileForPort(port)) &&
|
|
1548
1634
|
!existsSync(pidFileForPort(port))
|
|
1549
1635
|
) return port;
|
|
@@ -1580,11 +1666,11 @@ export async function startChrome({
|
|
|
1580
1666
|
const { requestedProfileName, resolvedProfileName } = resolveStartProfileName({ profileName, taskName, defaultProfileName });
|
|
1581
1667
|
ensureCacheDir();
|
|
1582
1668
|
|
|
1583
|
-
// Clean up before counting, so the cap reflects browsers that are
|
|
1584
|
-
// browsers
|
|
1669
|
+
// Clean up before counting, so the cap reflects browsers that are still actively owned. Untracked
|
|
1670
|
+
// browsers and old browsers whose launcher has exited are safe to reclaim before reserving a slot.
|
|
1585
1671
|
const reaped = reapOrphanedChromes();
|
|
1586
1672
|
if (reaped.reaped.length) {
|
|
1587
|
-
console.error(`⟳ Reaped ${reaped.reaped.length}
|
|
1673
|
+
console.error(`⟳ Reaped ${reaped.reaped.length} reclaimable managed browser${reaped.reaped.length === 1 ? '' : 's'} (${describePorts(reaped.reaped)})`);
|
|
1588
1674
|
try {
|
|
1589
1675
|
pruneChromeClones({ keepPorts: [normalizedPort] });
|
|
1590
1676
|
} catch {
|
|
@@ -1606,7 +1692,8 @@ export async function startChrome({
|
|
|
1606
1692
|
ownerToken: providedOwnerToken, includeGoogle, processes: candidates,
|
|
1607
1693
|
profileName: resolvedProfileName, headless, forceProfileSync,
|
|
1608
1694
|
});
|
|
1609
|
-
|
|
1695
|
+
const foundEndpoint = found ? await browserWSEndpoint(found.port) : null;
|
|
1696
|
+
if (found && foundEndpoint) {
|
|
1610
1697
|
reusable = found;
|
|
1611
1698
|
normalizedPort = found.port;
|
|
1612
1699
|
}
|
|
@@ -1627,7 +1714,21 @@ export async function startChrome({
|
|
|
1627
1714
|
try {
|
|
1628
1715
|
cleanupStaleManagedStateForPort(normalizedPort);
|
|
1629
1716
|
|
|
1630
|
-
|
|
1717
|
+
const endpoint = await browserWSEndpoint(normalizedPort);
|
|
1718
|
+
const occupied = !endpoint && await isPortOccupied(normalizedPort);
|
|
1719
|
+
if (endpoint || occupied) {
|
|
1720
|
+
// A non-CDP listener is never an adoption candidate, even if stale
|
|
1721
|
+
// managed state happens to match this port and owner token.
|
|
1722
|
+
if (occupied) {
|
|
1723
|
+
if (!autoAllocatePort) {
|
|
1724
|
+
throw new Error(
|
|
1725
|
+
`Port :${normalizedPort} is already in use, but it is not a Browser Tools managed browser. Use a different --port or stop that listener manually.`,
|
|
1726
|
+
);
|
|
1727
|
+
}
|
|
1728
|
+
assertManagedBrowserCapacity();
|
|
1729
|
+
normalizedPort = await findAvailablePort(normalizedPort + 1);
|
|
1730
|
+
continue;
|
|
1731
|
+
}
|
|
1631
1732
|
const safety = managedBrowserSafetyForPort(normalizedPort);
|
|
1632
1733
|
const state = readManagedStateForPort(normalizedPort);
|
|
1633
1734
|
const reuse = managedBrowserReuseDecision({
|
|
@@ -1812,11 +1913,19 @@ export async function startChrome({
|
|
|
1812
1913
|
ownerTokenGenerated: false,
|
|
1813
1914
|
};
|
|
1814
1915
|
}
|
|
1815
|
-
const
|
|
1816
|
-
if (!
|
|
1916
|
+
const launchedEndpoint = await waitForChromeEndpoint(normalizedPort, { timeoutMs: CHROME_READY_TIMEOUT_MS });
|
|
1917
|
+
if (!launchedEndpoint) {
|
|
1817
1918
|
stopChrome({ port: normalizedPort, ownerToken: effectiveOwnerToken, ignorePortLock: true });
|
|
1818
1919
|
throw new Error(`Failed to connect to Chrome after ${Math.round(CHROME_READY_TIMEOUT_MS / 1000)}s`);
|
|
1819
1920
|
}
|
|
1921
|
+
const launchedState = readManagedStateForPort(normalizedPort);
|
|
1922
|
+
const launchedSafety = managedBrowserSafetyForPort(normalizedPort);
|
|
1923
|
+
if (!launchedSafety.ok || Number(launchedState?.pid) !== Number(proc?.pid) || !devToolsActivePortMatches(launchedState?.userDataDir, launchedEndpoint)) {
|
|
1924
|
+
stopChrome({ port: normalizedPort, ownerToken: effectiveOwnerToken, ignorePortLock: true });
|
|
1925
|
+
throw new Error(
|
|
1926
|
+
`Chrome reported ready on :${normalizedPort}, but the responding process was not verified as the managed launch (${launchedSafety.reason || 'pid-mismatch'}).`,
|
|
1927
|
+
);
|
|
1928
|
+
}
|
|
1820
1929
|
return {
|
|
1821
1930
|
status: 'started',
|
|
1822
1931
|
port: normalizedPort,
|
|
@@ -2067,12 +2176,20 @@ function processStartIdentity(pid) {
|
|
|
2067
2176
|
if (!Number.isInteger(normalizedPid) || normalizedPid < 1) return null;
|
|
2068
2177
|
const result = spawnSync(
|
|
2069
2178
|
'ps',
|
|
2070
|
-
['-p', String(normalizedPid), '-o', 'lstart='
|
|
2071
|
-
{
|
|
2179
|
+
['-p', String(normalizedPid), '-o', 'lstart='],
|
|
2180
|
+
{
|
|
2181
|
+
encoding: 'utf-8',
|
|
2182
|
+
// BSD ps formats lstart through the caller's locale and timezone. Canonicalize both so two
|
|
2183
|
+
// processes observing the same live launcher hash the same immutable start metadata.
|
|
2184
|
+
env: { ...process.env, LC_ALL: 'C', LANG: 'C', LC_TIME: 'C', TZ: 'UTC' },
|
|
2185
|
+
},
|
|
2072
2186
|
);
|
|
2073
2187
|
if (result.error || result.status !== 0) return null;
|
|
2074
|
-
const
|
|
2075
|
-
if (!
|
|
2188
|
+
const startedAt = result.stdout.trim();
|
|
2189
|
+
if (!startedAt) return null;
|
|
2190
|
+
// PID and kernel-reported start time stay fixed for the process lifetime. Command and argv do not:
|
|
2191
|
+
// process.title can rewrite them while the same live process continues owning the browser.
|
|
2192
|
+
const identity = `${normalizedPid}\n${startedAt}`;
|
|
2076
2193
|
return createHash('sha256').update(identity, 'utf8').digest('hex');
|
|
2077
2194
|
}
|
|
2078
2195
|
|
package/scripts/stop.mjs
CHANGED
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
* scripts/stop.mjs --port 9223
|
|
9
9
|
* scripts/stop.mjs --clean
|
|
10
10
|
* scripts/stop.mjs --dry-run
|
|
11
|
-
* scripts/stop.mjs --prune (reap
|
|
12
|
-
* scripts/stop.mjs --reap (kill managed browsers
|
|
11
|
+
* scripts/stop.mjs --prune (reap leftovers, then remove all cached clones not in use)
|
|
12
|
+
* scripts/stop.mjs --reap (kill reclaimable managed browsers)
|
|
13
13
|
* scripts/stop.mjs --reap --dry-run (list them without killing anything)
|
|
14
14
|
* scripts/stop.mjs --status (show how many managed browsers are running)
|
|
15
15
|
* scripts/stop.mjs --owner-token "$BROWSER_TOOLS_OWNER_TOKEN"
|
|
@@ -35,7 +35,7 @@ const ownerToken = parseOwnerToken(args);
|
|
|
35
35
|
|
|
36
36
|
function reportReaped(reaped, wasDryRun) {
|
|
37
37
|
if (!reaped.length) {
|
|
38
|
-
console.log('No
|
|
38
|
+
console.log('No reclaimable managed browsers found.');
|
|
39
39
|
return;
|
|
40
40
|
}
|
|
41
41
|
for (const entry of reaped) {
|