@amaster.ai/pi-browser-use 0.1.1-beta.0

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,140 @@
1
+ # @amaster.ai/pi-browser-use
2
+
3
+ pi-coding-agent extension that wraps [chrome-devtools-mcp](https://github.com/ChromeDevTools/chrome-devtools-mcp), exposing all browser automation tools with a unified `browser_` prefix.
4
+
5
+ ## Features
6
+
7
+ - **pi-coding-agent extension** — registers tools via `pi.registerTool()`, managed by the agent lifecycle
8
+ - **Dynamic tool discovery** — automatically proxies all upstream chrome-devtools-mcp tools with `browser_` prefix
9
+ - **Tool description augmentation** — adds usage hints for key tools (click, fill, press_key, etc.)
10
+ - **Result post-processing** — strips embedded snapshots, detects overlay/stale element issues
11
+ - **Optional visual analysis** — `browser_analyze_screenshot` via configurable vision model
12
+ - **Standalone mode** — also runnable as an independent MCP server via CLI
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ bun add @amaster.ai/pi-browser-use
18
+ ```
19
+
20
+ Requires Node.js >= 20, Chrome (stable or newer), and `@earendil-works/pi-coding-agent >= 0.74.0`.
21
+
22
+ ## Usage
23
+
24
+ ### As pi-coding-agent Extension (Recommended)
25
+
26
+ Install the package and pi-coding-agent will automatically discover and load the extension. All browser tools are registered on `session_start`.
27
+
28
+ ```bash
29
+ bun add @amaster.ai/pi-browser-use
30
+ ```
31
+
32
+ Configure via `config.json` in the working directory under the `"pi-browser-use"` key:
33
+
34
+ ```json
35
+ {
36
+ "pi-browser-use": {
37
+ "headless": true,
38
+ "channel": "stable",
39
+ "viewport": "1280x720",
40
+ "experimentalVision": true
41
+ }
42
+ }
43
+ ```
44
+
45
+ ### As Standalone MCP Server (CLI)
46
+
47
+ ```bash
48
+ npx @amaster.ai/pi-browser-use --headless --viewport=1280x720
49
+ ```
50
+
51
+ Or with a config file:
52
+
53
+ ```bash
54
+ npx @amaster.ai/pi-browser-use --config path/to/config.json
55
+ ```
56
+
57
+ ## Configuration
58
+
59
+ ### Browser
60
+
61
+ | Option | Type | Default | Description |
62
+ |--------|------|---------|-------------|
63
+ | `headless` | `boolean` | `false` | Run browser in headless mode |
64
+ | `channel` | `string` | — | Chrome channel: `canary`, `dev`, `beta`, `stable` |
65
+ | `browserUrl` | `string` | — | Connect to existing browser via URL |
66
+ | `wsEndpoint` | `string` | — | Connect via WebSocket endpoint |
67
+ | `executablePath` | `string` | — | Path to Chrome executable |
68
+ | `viewport` | `string` | — | Viewport size, e.g. `1280x720` |
69
+ | `isolated` | `boolean` | `false` | Use isolated browser profile |
70
+ | `userDataDir` | `string` | — | Custom user data directory |
71
+ | `autoConnect` | `boolean` | `false` | Auto-connect to running browser |
72
+
73
+ ### Categories
74
+
75
+ | Option | Type | Default | Description |
76
+ |--------|------|---------|-------------|
77
+ | `categoryPerformance` | `boolean` | `false` | Enable performance tools |
78
+ | `categoryNetwork` | `boolean` | `true` | Enable network tools |
79
+ | `categoryEmulation` | `boolean` | `true` | Enable emulation tools |
80
+ | `categoryExtensions` | `boolean` | `false` | Enable extension tools |
81
+
82
+ ### Experimental
83
+
84
+ | Option | Type | Default | Description |
85
+ |--------|------|---------|-------------|
86
+ | `experimentalVision` | `boolean` | `true` | Enable vision tools (click_at) |
87
+ | `experimentalScreencast` | `boolean` | `false` | Enable screencast |
88
+ | `experimentalMemory` | `boolean` | `false` | Enable memory snapshots |
89
+
90
+ ### Privacy
91
+
92
+ | Option | Type | Default | Description |
93
+ |--------|------|---------|-------------|
94
+ | `usageStatistics` | `boolean` | `false` | Send usage statistics |
95
+ | `performanceCrux` | `boolean` | `false` | Enable CrUX performance data |
96
+
97
+ ### Vision Model (Optional)
98
+
99
+ Enable `browser_analyze_screenshot` by providing a vision model config in `config.json`:
100
+
101
+ ```json
102
+ {
103
+ "pi-browser-use": {
104
+ "visionModel": {
105
+ "provider": "openai",
106
+ "model": "gpt-4o",
107
+ "apiKey": "sk-...",
108
+ "baseUrl": "https://api.openai.com/v1"
109
+ }
110
+ }
111
+ }
112
+ ```
113
+
114
+ Supported providers: `openai`, `anthropic`, or any OpenAI-compatible API. API keys can also be set via environment variables (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`).
115
+
116
+ ## Tool Augmentation
117
+
118
+ Key tools receive additional usage hints in their descriptions:
119
+
120
+ | Tool | Hint |
121
+ |------|------|
122
+ | `browser_click` | Use element uid from snapshot; UIDs invalidated after action |
123
+ | `browser_fill` | Does not work on canvas/custom widgets |
124
+ | `browser_press_key` | Accepts single key name only |
125
+ | `browser_take_snapshot` | Call first to get uids, and after every state-changing action |
126
+ | `browser_navigate_page` | Call take_snapshot after navigation |
127
+
128
+ ## Result Post-Processing
129
+
130
+ - **Snapshot stripping** — Removes embedded accessibility tree snapshots from non-snapshot tool responses to prevent token bloat
131
+ - **Overlay detection** — When a click is blocked by an overlay/popup, appends a hint to dismiss it first
132
+ - **Stale element detection** — When element references are stale, appends a hint to refresh the snapshot
133
+
134
+ ## Excluded Tools
135
+
136
+ - `lighthouse_audit` — Filtered out at the proxy level
137
+
138
+ ## License
139
+
140
+ Apache-2.0
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Optional vision-model integration.
3
+ *
4
+ * Takes a screenshot via the upstream take_screenshot tool, sends it to a
5
+ * vision model, and returns the analysis as text. This lets the LLM identify
6
+ * elements by visual attributes (color, layout, coordinates) when the
7
+ * accessibility tree is insufficient.
8
+ *
9
+ * Two calling modes:
10
+ * - Extension mode: uses pi-ai's complete() via the model registry (no raw fetch)
11
+ * - CLI mode: uses raw fetch to OpenAI-compatible APIs (createFetchVisionCaller)
12
+ */
13
+ import type { VisionModelConfig } from './config.js';
14
+ import type { DevToolsClient } from './index.js';
15
+ /** System prompt for the vision analysis model. */
16
+ export declare const VISUAL_SYSTEM_PROMPT = "You are a Visual Analysis Agent. You receive a screenshot of a browser page and an instruction.\n\nYour job is to ANALYZE the screenshot and provide precise information that a browser automation agent can act on.\n\nCOORDINATE SYSTEM:\n- Coordinates are pixel-based relative to the viewport\n- (0,0) is top-left of the visible area\n- Estimate element positions from the screenshot\n\nRESPONSE FORMAT:\n- For coordinate identification: provide exact (x, y) pixel coordinates\n- For element identification: describe the element's visual location and appearance\n- For layout analysis: describe the spatial relationships between elements\n- Be concise and actionable\n\nIMPORTANT:\n- You are NOT performing actions \u2014 you are only providing visual analysis\n- Include coordinates when possible so the caller can use click_at(x, y)\n- If the element is not visible in the screenshot, say so explicitly";
17
+ /**
18
+ * Abstraction for calling a vision model.
19
+ * Extension mode and CLI mode each provide their own implementation.
20
+ */
21
+ export type VisionCaller = (instruction: string, imageBase64: string, mimeType: string) => Promise<string>;
22
+ /** Create a VisionCaller backed by raw fetch (OpenAI-compatible API). Used in CLI standalone mode. */
23
+ export declare function createFetchVisionCaller(visionConfig: VisionModelConfig): VisionCaller;
24
+ /**
25
+ * Capture a screenshot via the upstream tool and analyze it with the provided vision caller.
26
+ * The caller abstraction allows extension mode (pi-ai) and CLI mode (raw fetch) to share logic.
27
+ */
28
+ export declare function handleAnalyzeScreenshot(client: DevToolsClient, callVision: VisionCaller, args: Record<string, unknown>): Promise<{
29
+ content: Array<{
30
+ type: string;
31
+ text: string;
32
+ }>;
33
+ isError?: boolean;
34
+ }>;
35
+ //# sourceMappingURL=analyze-screenshot.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analyze-screenshot.d.ts","sourceRoot":"","sources":["../src/analyze-screenshot.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,mDAAmD;AACnD,eAAO,MAAM,oBAAoB,24BAkBoC,CAAC;AAEtE;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,CACzB,WAAW,EAAE,MAAM,EACnB,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,KACb,OAAO,CAAC,MAAM,CAAC,CAAC;AA6BrB,sGAAsG;AACtG,wBAAgB,uBAAuB,CAAC,YAAY,EAAE,iBAAiB,GAAG,YAAY,CAqDrF;AAMD;;;GAGG;AACH,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,cAAc,EACtB,UAAU,EAAE,YAAY,EACxB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC5B,OAAO,CAAC;IAAE,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC,CAiEhF"}
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Optional vision-model integration.
3
+ *
4
+ * Takes a screenshot via the upstream take_screenshot tool, sends it to a
5
+ * vision model, and returns the analysis as text. This lets the LLM identify
6
+ * elements by visual attributes (color, layout, coordinates) when the
7
+ * accessibility tree is insufficient.
8
+ *
9
+ * Two calling modes:
10
+ * - Extension mode: uses pi-ai's complete() via the model registry (no raw fetch)
11
+ * - CLI mode: uses raw fetch to OpenAI-compatible APIs (createFetchVisionCaller)
12
+ */
13
+ /** System prompt for the vision analysis model. */
14
+ export const VISUAL_SYSTEM_PROMPT = `You are a Visual Analysis Agent. You receive a screenshot of a browser page and an instruction.
15
+
16
+ Your job is to ANALYZE the screenshot and provide precise information that a browser automation agent can act on.
17
+
18
+ COORDINATE SYSTEM:
19
+ - Coordinates are pixel-based relative to the viewport
20
+ - (0,0) is top-left of the visible area
21
+ - Estimate element positions from the screenshot
22
+
23
+ RESPONSE FORMAT:
24
+ - For coordinate identification: provide exact (x, y) pixel coordinates
25
+ - For element identification: describe the element's visual location and appearance
26
+ - For layout analysis: describe the spatial relationships between elements
27
+ - Be concise and actionable
28
+
29
+ IMPORTANT:
30
+ - You are NOT performing actions — you are only providing visual analysis
31
+ - Include coordinates when possible so the caller can use click_at(x, y)
32
+ - If the element is not visible in the screenshot, say so explicitly`;
33
+ function getApiKeyFromEnv(provider) {
34
+ const envMap = {
35
+ openai: 'OPENAI_API_KEY',
36
+ anthropic: 'ANTHROPIC_API_KEY',
37
+ google: 'GOOGLE_API_KEY',
38
+ };
39
+ const envVar = envMap[provider.toLowerCase()];
40
+ return envVar ? process.env[envVar] : undefined;
41
+ }
42
+ function getDefaultBaseUrl(provider) {
43
+ const urlMap = {
44
+ openai: 'https://api.openai.com/v1',
45
+ anthropic: 'https://api.anthropic.com/v1',
46
+ };
47
+ return urlMap[provider.toLowerCase()] ?? `https://api.${provider}.com/v1`;
48
+ }
49
+ /** Create a VisionCaller backed by raw fetch (OpenAI-compatible API). Used in CLI standalone mode. */
50
+ export function createFetchVisionCaller(visionConfig) {
51
+ return async (instruction, imageBase64, mimeType) => {
52
+ const apiKey = visionConfig.apiKey ?? getApiKeyFromEnv(visionConfig.provider);
53
+ if (!apiKey) {
54
+ throw new Error(`No API key for vision model provider "${visionConfig.provider}". ` +
55
+ `Set apiKey in visionModel config or the appropriate environment variable.`);
56
+ }
57
+ const baseUrl = visionConfig.baseUrl ?? getDefaultBaseUrl(visionConfig.provider);
58
+ const messages = [
59
+ { role: 'system', content: VISUAL_SYSTEM_PROMPT },
60
+ {
61
+ role: 'user',
62
+ content: [
63
+ {
64
+ type: 'text',
65
+ text: `Analyze this screenshot and respond to the following instruction:\n\n${instruction}`,
66
+ },
67
+ {
68
+ type: 'image_url',
69
+ image_url: { url: `data:${mimeType};base64,${imageBase64}` },
70
+ },
71
+ ],
72
+ },
73
+ ];
74
+ const response = await fetch(`${baseUrl}/chat/completions`, {
75
+ method: 'POST',
76
+ headers: {
77
+ 'Content-Type': 'application/json',
78
+ Authorization: `Bearer ${apiKey}`,
79
+ },
80
+ body: JSON.stringify({
81
+ model: visionConfig.model,
82
+ messages,
83
+ temperature: 0,
84
+ max_tokens: 2048,
85
+ }),
86
+ });
87
+ if (!response.ok) {
88
+ const body = await response.text();
89
+ throw new Error(`Vision model API error (${response.status}): ${body}`);
90
+ }
91
+ const data = (await response.json());
92
+ return data.choices?.[0]?.message?.content ?? '';
93
+ };
94
+ }
95
+ // ---------------------------------------------------------------------------
96
+ // Main handler (framework-agnostic)
97
+ // ---------------------------------------------------------------------------
98
+ /**
99
+ * Capture a screenshot via the upstream tool and analyze it with the provided vision caller.
100
+ * The caller abstraction allows extension mode (pi-ai) and CLI mode (raw fetch) to share logic.
101
+ */
102
+ export async function handleAnalyzeScreenshot(client, callVision, args) {
103
+ const instruction = String(args.instruction ?? '');
104
+ try {
105
+ const screenshotResult = await client.callTool('take_screenshot', {});
106
+ let imageBase64 = '';
107
+ let mimeType = 'image/png';
108
+ if (screenshotResult.content && Array.isArray(screenshotResult.content)) {
109
+ for (const item of screenshotResult.content) {
110
+ if (item.type === 'image' && item.data) {
111
+ imageBase64 = item.data;
112
+ mimeType = item.mimeType ?? 'image/png';
113
+ break;
114
+ }
115
+ }
116
+ }
117
+ if (!imageBase64) {
118
+ return {
119
+ content: [
120
+ {
121
+ type: 'text',
122
+ text: 'Failed to capture screenshot for visual analysis. Use accessibility tree elements instead.',
123
+ },
124
+ ],
125
+ isError: true,
126
+ };
127
+ }
128
+ const analysis = await callVision(instruction, imageBase64, mimeType);
129
+ if (!analysis) {
130
+ return {
131
+ content: [
132
+ {
133
+ type: 'text',
134
+ text: 'Visual model returned no analysis. Use accessibility tree elements instead.',
135
+ },
136
+ ],
137
+ isError: true,
138
+ };
139
+ }
140
+ return {
141
+ content: [{ type: 'text', text: `Visual Analysis Result:\n${analysis}` }],
142
+ };
143
+ }
144
+ catch (error) {
145
+ const errorMsg = error instanceof Error ? error.message : String(error);
146
+ const isModelError = errorMsg.includes('404') ||
147
+ errorMsg.includes('403') ||
148
+ errorMsg.includes('not found') ||
149
+ errorMsg.includes('permission');
150
+ const fallbackMsg = isModelError
151
+ ? 'Visual analysis model is not available. Use accessibility tree elements (uids from take_snapshot) for all interactions instead.'
152
+ : `Visual analysis failed: ${errorMsg}. Use accessibility tree elements instead.`;
153
+ return {
154
+ content: [{ type: 'text', text: fallbackMsg }],
155
+ isError: true,
156
+ };
157
+ }
158
+ }
159
+ //# sourceMappingURL=analyze-screenshot.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analyze-screenshot.js","sourceRoot":"","sources":["../src/analyze-screenshot.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAKH,mDAAmD;AACnD,MAAM,CAAC,MAAM,oBAAoB,GAAG;;;;;;;;;;;;;;;;;;qEAkBiC,CAAC;AAqBtE,SAAS,gBAAgB,CAAC,QAAgB;IACxC,MAAM,MAAM,GAA2B;QACrC,MAAM,EAAE,gBAAgB;QACxB,SAAS,EAAE,mBAAmB;QAC9B,MAAM,EAAE,gBAAgB;KACzB,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IAC9C,OAAO,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAClD,CAAC;AAED,SAAS,iBAAiB,CAAC,QAAgB;IACzC,MAAM,MAAM,GAA2B;QACrC,MAAM,EAAE,2BAA2B;QACnC,SAAS,EAAE,8BAA8B;KAC1C,CAAC;IACF,OAAO,MAAM,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,IAAI,eAAe,QAAQ,SAAS,CAAC;AAC5E,CAAC;AAED,sGAAsG;AACtG,MAAM,UAAU,uBAAuB,CAAC,YAA+B;IACrE,OAAO,KAAK,EAAE,WAAmB,EAAE,WAAmB,EAAE,QAAgB,EAAmB,EAAE;QAC3F,MAAM,MAAM,GAAG,YAAY,CAAC,MAAM,IAAI,gBAAgB,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;QAC9E,IAAI,CAAC,MAAM,EAA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AI,EAAE,MAAM;wBACZ,IAAI,EAAE,6EAA6E;qBACpF;iBACF;gBACD,OAAO,EAAE,IAAI;aACd,CAAC;QACJ,CAAC;QAED,OAAO;YACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,4BAA4B,QAAQ,EAAE,EAAE,CAAC;SAC1E,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,QAAQ,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAExE,MAAM,YAAY,GAChB,QAAQ,CAAC,QAAQ,CAAC,KAAK,CAAC;YACxB,QAAQ,CAAC,QAAQ,CAAC,KAAK,CAAC;YACxB,QAAQ,CAAC,QAAQ,CAAC,WAAW,CAAC;YAC9B,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;QAElC,MAAM,WAAW,GAAG,YAAY;YAC9B,CAAC,CAAC,iIAAiI;YACnI,CAAC,CAAC,2BAA2B,QAAQ,4CAA4C,CAAC;QAEpF,OAAO;YACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;YAC9C,OAAO,EAAE,IAAI;SACd,CAAC;IACJ,CAAC;AACH,CAAC"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Standalone MCP server mode.
4
+ *
5
+ * Runs pi-browser-use as a standalone process that speaks MCP over stdio.
6
+ * Used when pi-browser-use is configured as an external MCP server (e.g. in mcp.json)
7
+ * rather than loaded as a pi-coding-agent extension.
8
+ */
9
+ import type { BrowserUseConfig } from './config.js';
10
+ export declare function parseArgs(argv: string[]): BrowserUseConfig;
11
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA;;;;;;GAMG;AAOH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAuBpD,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,gBAAgB,CAmC1D"}
package/dist/cli.js ADDED
@@ -0,0 +1,133 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Standalone MCP server mode.
4
+ *
5
+ * Runs pi-browser-use as a standalone process that speaks MCP over stdio.
6
+ * Used when pi-browser-use is configured as an external MCP server (e.g. in mcp.json)
7
+ * rather than loaded as a pi-coding-agent extension.
8
+ */
9
+ import { readFileSync } from 'node:fs';
10
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
11
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
12
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
13
+ import { createFetchVisionCaller, handleAnalyzeScreenshot } from './analyze-screenshot.js';
14
+ import { DevToolsClient } from './index.js';
15
+ import { augmentToolDescription, extractTextContent, postProcessToolResult, } from './tool-augment.js';
16
+ const TOOL_PREFIX = 'browser_';
17
+ const EXCLUDED_TOOLS = new Set([
18
+ 'lighthouse_audit',
19
+ 'performance_analyze_insight',
20
+ 'performance_start_trace',
21
+ 'performance_stop_trace',
22
+ 'screencast_start',
23
+ 'screencast_stop',
24
+ 'install_extension',
25
+ 'list_extensions',
26
+ 'reload_extension',
27
+ 'trigger_extension_action',
28
+ 'uninstall_extension',
29
+ ]);
30
+ export function parseArgs(argv) {
31
+ const config = {};
32
+ let i = 0;
33
+ while (i < argv.length) {
34
+ const arg = argv[i];
35
+ if (arg === '--config' && argv[i + 1] != null) {
36
+ const raw = readFileSync(argv[i + 1], 'utf-8');
37
+ const parsed = JSON.parse(raw);
38
+ const section = (parsed['pi-browser-use'] ?? parsed);
39
+ Object.assign(config, section);
40
+ i += 2;
41
+ continue;
42
+ }
43
+ const match = arg.match(/^--([a-z-]+)(?:=(.+))?$/);
44
+ if (match) {
45
+ const key = match[1];
46
+ const value = match[2];
47
+ const camelKey = key.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
48
+ if (value === undefined || value === 'true') {
49
+ config[camelKey] = true;
50
+ }
51
+ else if (value === 'false') {
52
+ config[camelKey] = false;
53
+ }
54
+ else {
55
+ config[camelKey] = value;
56
+ }
57
+ }
58
+ i++;
59
+ }
60
+ return config;
61
+ }
62
+ async function main() {
63
+ const config = parseArgs(process.argv.slice(2));
64
+ const client = new DevToolsClient(config);
65
+ await client.connect();
66
+ const toolNameMap = new Map();
67
+ const server = new Server({ name: 'pi-browser-use', version: '0.1.0' }, { capabilities: { tools: {} } });
68
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
69
+ const upstreamTools = await client.listAllTools();
70
+ const tools = [];
71
+ toolNameMap.clear();
72
+ for (const tool of upstreamTools) {
73
+ if (EXCLUDED_TOOLS.has(tool.name))
74
+ continue;
75
+ const prefixedName = `${TOOL_PREFIX}${tool.name}`;
76
+ toolNameMap.set(prefixedName, tool.name);
77
+ tools.push({
78
+ ...tool,
79
+ name: prefixedName,
80
+ description: augmentToolDescription(tool.name, tool.description ?? ''),
81
+ });
82
+ }
83
+ if (config.visionModel) {
84
+ const name = `${TOOL_PREFIX}analyze_screenshot`;
85
+ toolNameMap.set(name, 'analyze_screenshot');
86
+ tools.push({
87
+ name,
88
+ description: 'Analyze the current page visually using a screenshot.',
89
+ inputSchema: {
90
+ type: 'object',
91
+ properties: {
92
+ instruction: {
93
+ type: 'string',
94
+ description: 'What to identify or analyze visually.',
95
+ },
96
+ },
97
+ required: ['instruction'],
98
+ },
99
+ });
100
+ }
101
+ return { tools };
102
+ });
103
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
104
+ const { name, arguments: args } = request.params;
105
+ const originalName = toolNameMap.get(name);
106
+ if (!originalName)
107
+ throw new Error(`Unknown tool: ${name}`);
108
+ if (originalName === 'analyze_screenshot' && config.visionModel) {
109
+ const callVision = createFetchVisionCaller(config.visionModel);
110
+ return await handleAnalyzeScreenshot(client, callVision, args ?? {});
111
+ }
112
+ const result = await client.callTool(originalName, args ?? {});
113
+ const textContent = extractTextContent(result.content);
114
+ const processed = postProcessToolResult(originalName, textContent);
115
+ if (processed !== textContent) {
116
+ const newContent = (result.content ?? []).map((item) => {
117
+ if (item.type === 'text') {
118
+ return { ...item, text: processed };
119
+ }
120
+ return item;
121
+ });
122
+ return { ...result, content: newContent };
123
+ }
124
+ return result;
125
+ });
126
+ const transport = new StdioServerTransport();
127
+ await server.connect(transport);
128
+ }
129
+ main().catch((error) => {
130
+ console.error(`[pi-browser-use] Fatal error: ${error}`);
131
+ process.exit(1);
132
+ });
133
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA;;;;;;GAMG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,oCAAoC,CAAC;AACnG,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAE3F,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EACL,sBAAsB,EACtB,kBAAkB,EAClB,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAE3B,MAAM,WAAW,GAAG,UAAU,CAAC;AAC/B,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC;IAC7B,kBAAkB;IAClB,6BAA6B;IAC7B,yBAAyB;IACzB,wBAAwB;IACxB,kBAAkB;IAClB,iBAAiB;IACjB,mBAAmB;IACnB,iBAAiB;IACjB,kBAAkB;IAClB,0BAA0B;IAC1B,qB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AAC;QAC/D,MAAM,WAAW,GAAG,kBAAkB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACvD,MAAM,SAAS,GAAG,qBAAqB,CAAC,YAAY,EAAE,WAAW,CAAC,CAAC;QAEnE,IAAI,SAAS,KAAK,WAAW,EAAE,CAAC;YAC9B,MAAM,UAAU,GAAG,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;gBACrD,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;oBACzB,OAAO,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;gBACtC,CAAC;gBACD,OAAO,IAAI,CAAC;YACd,CAAC,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,UAAU,EAA6B,CAAC;QACvE,CAAC;QAED,OAAO,MAAiC,CAAC;IAC3C,CAAC,CAAC,CAAC;IAEH,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;IAC7C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;AAClC,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,iCAAiC,KAAK,EAAE,CAAC,CAAC;IACxD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,37 @@
1
+ /** Vision model used by the optional analyze_screenshot tool. */
2
+ export interface VisionModelConfig {
3
+ provider: string;
4
+ model: string;
5
+ apiKey?: string;
6
+ baseUrl?: string;
7
+ }
8
+ /** Configuration for the chrome-devtools-mcp upstream process. */
9
+ export interface BrowserUseConfig {
10
+ headless?: boolean;
11
+ channel?: 'canary' | 'dev' | 'beta' | 'stable';
12
+ browserUrl?: string;
13
+ wsEndpoint?: string;
14
+ wsHeaders?: string;
15
+ executablePath?: string;
16
+ viewport?: string;
17
+ isolated?: boolean;
18
+ userDataDir?: string;
19
+ autoConnect?: boolean;
20
+ categoryPerformance?: boolean;
21
+ categoryNetwork?: boolean;
22
+ categoryEmulation?: boolean;
23
+ categoryExtensions?: boolean;
24
+ experimentalVision?: boolean;
25
+ experimentalScreencast?: boolean;
26
+ experimentalMemory?: boolean;
27
+ visionModel?: VisionModelConfig;
28
+ usageStatistics?: boolean;
29
+ performanceCrux?: boolean;
30
+ slim?: boolean;
31
+ extraArgs?: string[];
32
+ }
33
+ /** Merge user config over sane defaults. */
34
+ export declare function resolveConfig(config?: BrowserUseConfig): BrowserUseConfig;
35
+ /** Convert config into CLI flags for the chrome-devtools-mcp subprocess. */
36
+ export declare function configToArgs(config: BrowserUseConfig): string[];
37
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,kEAAkE;AAClE,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,QAAQ,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,CAAC;IAC/C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAE7B,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,sBAAsB,CAAC,EAAE,OAAO,CAAC;IACjC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAE7B,WAAW,CAAC,EAAE,iBAAiB,CAAC;IAEhC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,eAAe,CAAC,EAAE,OAAO,CAAC;IAE1B,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;CACtB;AAcD,4CAA4C;AAC5C,wBAAgB,aAAa,CAAC,MAAM,CAAC,EAAE,gBAAgB,GAAG,gBAAgB,CAEzE;AAED,4EAA4E;AAC5E,wBAAgB,YAAY,CAAC,MAAM,EAAE,gBAAgB,GAAG,MAAM,EAAE,CA+B/D"}
package/dist/config.js ADDED
@@ -0,0 +1,64 @@
1
+ const DEFAULTS = {
2
+ categoryPerformance: false,
3
+ categoryNetwork: true,
4
+ categoryEmulation: true,
5
+ categoryExtensions: false,
6
+ experimentalVision: true,
7
+ experimentalScreencast: false,
8
+ experimentalMemory: false,
9
+ usageStatistics: false,
10
+ performanceCrux: false,
11
+ };
12
+ /** Merge user config over sane defaults. */
13
+ export function resolveConfig(config) {
14
+ return { ...DEFAULTS, ...config };
15
+ }
16
+ /** Convert config into CLI flags for the chrome-devtools-mcp subprocess. */
17
+ export function configToArgs(config) {
18
+ const args = [];
19
+ const resolved = resolveConfig(config);
20
+ if (resolved.headless)
21
+ args.push('--headless');
22
+ if (resolved.channel)
23
+ args.push(`--channel=${resolved.channel}`);
24
+ if (resolved.browserUrl)
25
+ args.push(`--browser-url=${resolved.browserUrl}`);
26
+ if (resolved.wsEndpoint)
27
+ args.push(`--ws-endpoint=${resolved.wsEndpoint}`);
28
+ if (resolved.wsHeaders)
29
+ args.push(`--ws-headers=${resolved.wsHeaders}`);
30
+ if (resolved.executablePath)
31
+ args.push(`--executable-path=${resolved.executablePath}`);
32
+ if (resolved.viewport)
33
+ args.push(`--viewport=${resolved.viewport}`);
34
+ if (resolved.isolated)
35
+ args.push('--isolated');
36
+ if (resolved.userDataDir)
37
+ args.push(`--user-data-dir=${resolved.userDataDir}`);
38
+ if (resolved.autoConnect)
39
+ args.push('--auto-connect');
40
+ if (resolved.slim)
41
+ args.push('--slim');
42
+ if (resolved.categoryPerformance === false)
43
+ args.push('--category-performance=false');
44
+ if (resolved.categoryNetwork === false)
45
+ args.push('--category-network=false');
46
+ if (resolved.categoryEmulation === false)
47
+ args.push('--category-emulation=false');
48
+ if (resolved.categoryExtensions === true)
49
+ args.push('--category-extensions=true');
50
+ if (resolved.experimentalVision)
51
+ args.push('--experimental-vision');
52
+ if (resolved.experimentalScreencast)
53
+ args.push('--experimental-screencast');
54
+ if (resolved.experimentalMemory)
55
+ args.push('--experimental-memory');
56
+ if (resolved.usageStatistics === false)
57
+ args.push('--no-usage-statistics');
58
+ if (resolved.performanceCrux === false)
59
+ args.push('--no-performance-crux');
60
+ if (resolved.extraArgs)
61
+ args.push(...resolved.extraArgs);
62
+ return args;
63
+ }
64
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAuCA,MAAM,QAAQ,GAA8B;IAC1C,mBAAmB,EAAE,KAAK;IAC1B,eAAe,EAAE,IAAI;IACrB,iBAAiB,EAAE,IAAI;IACvB,kBAAkB,EAAE,KAAK;IACzB,kBAAkB,EAAE,IAAI;IACxB,sBAAsB,EAAE,KAAK;IAC7B,kBAAkB,EAAE,KAAK;IACzB,eAAe,EAAE,KAAK;IACtB,eAAe,EAAE,KAAK;CACvB,CAAC;AAEF,4CAA4C;AAC5C,MAAM,UAAU,aAAa,CAAC,MAAyB;IACrD,OA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IAAI;QAAE,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAEvC,IAAI,QAAQ,CAAC,mBAAmB,KAAK,KAAK;QAAE,IAAI,CAAC,IAAI,CAAC,8BAA8B,CAAC,CAAC;IACtF,IAAI,QAAQ,CAAC,eAAe,KAAK,KAAK;QAAE,IAAI,CAAC,IAAI,CAAC,0BAA0B,CAAC,CAAC;IAC9E,IAAI,QAAQ,CAAC,iBAAiB,KAAK,KAAK;QAAE,IAAI,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IAClF,IAAI,QAAQ,CAAC,kBAAkB,KAAK,IAAI;QAAE,IAAI,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IAElF,IAAI,QAAQ,CAAC,kBAAkB;QAAE,IAAI,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;IACpE,IAAI,QAAQ,CAAC,sBAAsB;QAAE,IAAI,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC;IAC5E,IAAI,QAAQ,CAAC,kBAAkB;QAAE,IAAI,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;IAEpE,IAAI,QAAQ,CAAC,eAAe,KAAK,KAAK;QAAE,IAAI,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;IAC3E,IAAI,QAAQ,CAAC,eAAe,KAAK,KAAK;QAAE,IAAI,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;IAE3E,IAAI,QAAQ,CAAC,SAAS;QAAE,IAAI,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC;IAEzD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,39 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import type { Tool } from '@modelcontextprotocol/sdk/types.js';
3
+ import { type BrowserUseConfig, configToArgs, resolveConfig, type VisionModelConfig } from './config.js';
4
+ export type { BrowserUseConfig, VisionModelConfig };
5
+ export { configToArgs, resolveConfig };
6
+ /**
7
+ * MCP client that spawns chrome-devtools-mcp as a subprocess and communicates
8
+ * over stdio. Owns the child-process lifecycle: connect() starts it, close() kills it.
9
+ */
10
+ export declare class DevToolsClient {
11
+ private client;
12
+ private transport;
13
+ private config;
14
+ constructor(config?: BrowserUseConfig);
15
+ connect(): Promise<void>;
16
+ listAllTools(): Promise<Tool[]>;
17
+ callTool(name: string, args: Record<string, unknown>): Promise<{
18
+ content?: Array<{
19
+ type: string;
20
+ text?: string;
21
+ data?: string;
22
+ mimeType?: string;
23
+ }>;
24
+ isError?: boolean;
25
+ }>;
26
+ close(): Promise<void>;
27
+ }
28
+ /**
29
+ * pi-coding-agent extension entry point.
30
+ *
31
+ * On session_start: spawns chrome-devtools-mcp, discovers upstream tools,
32
+ * and registers each one via pi.registerTool() with a "browser_" prefix.
33
+ * On session_shutdown: tears down the subprocess.
34
+ *
35
+ * Config is loaded from config.json["pi-browser-use"] in the working directory.
36
+ * If visionModel is configured, an additional analyze_screenshot tool is registered.
37
+ */
38
+ export default function browserUseExtension(pi: ExtensionAPI): void;
39
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAoB,MAAM,iCAAiC,CAAC;AAGtF,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,oCAAoC,CAAC;AAO/D,OAAO,EACL,KAAK,gBAAgB,EACrB,YAAY,EACZ,aAAa,EACb,KAAK,iBAAiB,EACvB,MAAM,aAAa,CAAC;AAOrB,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,CAAC;AAsBvC;;;GAGG;AACH,qBAAa,cAAc;IACzB,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,SAAS,CAAqC;IACtD,OAAO,CAAC,MAAM,CAAmB;gBAErB,MAAM,CAAC,EAAE,gBAAgB;IAI/B,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAkBxB,YAAY,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;IAgB/B,QAAQ,CACZ,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC5B,OAAO,CAAC;QACT,OAAO,CAAC,EAAE,KAAK,CAAC;YACd,IAAI,EAAE,MAAM,CAAC;YACb,IAAI,CAAC,EAAE,MAAM,CAAC;YACd,IAAI,CAAC,EAAE,MAAM,CAAC;YACd,QAAQ,CAAC,EAAE,MAAM,CAAC;SACnB,CAAC,CAAC;QACH,OAAO,CAAC,EAAE,OAAO,CAAC;KACnB,CAAC;IAgBI,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAO7B;AAiDD;;;;;;;;;GASG;AACH,MAAM,CAAC,OAAO,UAAU,mBAAmB,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CAqJlE"}
package/dist/index.js ADDED
@@ -0,0 +1,238 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { complete } from '@earendil-works/pi-ai';
4
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
5
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
6
+ import { Type } from 'typebox';
7
+ import { handleAnalyzeScreenshot, VISUAL_SYSTEM_PROMPT, } from './analyze-screenshot.js';
8
+ import { configToArgs, resolveConfig, } from './config.js';
9
+ import { augmentToolDescription, extractTextContent, postProcessToolResult, } from './tool-augment.js';
10
+ export { configToArgs, resolveConfig };
11
+ // All upstream tools are re-exported with this prefix to avoid name collisions with other extensions.
12
+ const TOOL_PREFIX = 'browser_';
13
+ // These upstream tools are noisy or slow; skip them during registration.
14
+ const EXCLUDED_TOOLS = new Set([
15
+ 'lighthouse_audit',
16
+ 'performance_analyze_insight',
17
+ 'performance_start_trace',
18
+ 'performance_stop_trace',
19
+ 'screencast_start',
20
+ 'screencast_stop',
21
+ 'install_extension',
22
+ 'list_extensions',
23
+ 'reload_extension',
24
+ 'trigger_extension_action',
25
+ 'uninstall_extension',
26
+ ]);
27
+ const MCP_TIMEOUT_MS = 60_000;
28
+ /**
29
+ * MCP client that spawns chrome-devtools-mcp as a subprocess and communicates
30
+ * over stdio. Owns the child-process lifecycle: connect() starts it, close() kills it.
31
+ */
32
+ export class DevToolsClient {
33
+ client = null;
34
+ transport = null;
35
+ config;
36
+ constructor(config) {
37
+ this.config = resolveConfig(config);
38
+ }
39
+ async connect() {
40
+ const args = configToArgs(this.config);
41
+ this.transport = new StdioClientTransport({
42
+ command: 'npx',
43
+ args: ['-y', 'chrome-devtools-mcp@latest', ...args],
44
+ stderr: 'pipe',
45
+ });
46
+ this.client = new Client({ name: 'pi-browser-use', version: '0.1.0' }, { capabilities: {} });
47
+ this.transport.onerror = (error) => {
48
+ console.error(`[pi-browser-use] chrome-devtools-mcp transport error: ${error.message}`);
49
+ };
50
+ await this.client.connect(this.transport);
51
+ }
52
+ async listAllTools() {
53
+ if (!this.client)
54
+ throw new Error('Client not connected');
55
+ const allTools = [];
56
+ let cursor;
57
+ do {
58
+ const result = await this.client.listTools(cursor ? { cursor } : undefined, {
59
+ timeout: MCP_TIMEOUT_MS,
60
+ });
61
+ allTools.push(...result.tools);
62
+ cursor = result.nextCursor;
63
+ } while (cursor);
64
+ return allTools;
65
+ }
66
+ async callTool(name, args) {
67
+ if (!this.client)
68
+ throw new Error('Client not connected');
69
+ return (await this.client.callTool({ name, arguments: args }, undefined, {
70
+ timeout: MCP_TIMEOUT_MS,
71
+ }));
72
+ }
73
+ async close() {
74
+ if (this.client) {
75
+ await this.client.close();
76
+ this.client = null;
77
+ }
78
+ this.transport = null;
79
+ }
80
+ }
81
+ /** Read the pi-browser-use section from config.json in the working directory. */
82
+ function loadConfigFromFile() {
83
+ try {
84
+ const configPath = resolve(process.cwd(), 'config.json');
85
+ const raw = readFileSync(configPath, 'utf-8');
86
+ const parsed = JSON.parse(raw);
87
+ return (parsed['pi-browser-use'] ?? {});
88
+ }
89
+ catch {
90
+ return {};
91
+ }
92
+ }
93
+ /** Convert upstream MCP result into pi-agent TextContent[], applying post-processing. */
94
+ function toTextContent(result, originalName) {
95
+ const textContent = extractTextContent(result.content);
96
+ const processed = postProcessToolResult(originalName, textContent);
97
+ const content = [];
98
+ if (processed !== textContent) {
99
+ content.push({ type: 'text', text: processed });
100
+ }
101
+ else if (result.content) {
102
+ for (const item of result.content) {
103
+ if (item.type === 'text' && item.text) {
104
+ content.push({ type: 'text', text: item.text });
105
+ }
106
+ }
107
+ }
108
+ if (content.length === 0) {
109
+ content.push({ type: 'text', text: '' });
110
+ }
111
+ return result.isError ? { content, isError: true } : { content };
112
+ }
113
+ /**
114
+ * pi-coding-agent extension entry point.
115
+ *
116
+ * On session_start: spawns chrome-devtools-mcp, discovers upstream tools,
117
+ * and registers each one via pi.registerTool() with a "browser_" prefix.
118
+ * On session_shutdown: tears down the subprocess.
119
+ *
120
+ * Config is loaded from config.json["pi-browser-use"] in the working directory.
121
+ * If visionModel is configured, an additional analyze_screenshot tool is registered.
122
+ */
123
+ export default function browserUseExtension(pi) {
124
+ const config = resolveConfig(loadConfigFromFile());
125
+ const client = new DevToolsClient(config);
126
+ let connected = false;
127
+ async function ensureConnected() {
128
+ if (!connected) {
129
+ await client.connect();
130
+ connected = true;
131
+ }
132
+ }
133
+ async function registerUpstreamTools() {
134
+ await ensureConnected();
135
+ const upstreamTools = await client.listAllTools();
136
+ for (const tool of upstreamTools) {
137
+ if (EXCLUDED_TOOLS.has(tool.name))
138
+ continue;
139
+ const prefixedName = `${TOOL_PREFIX}${tool.name}`;
140
+ const originalName = tool.name;
141
+ const description = augmentToolDescription(originalName, tool.description ?? '');
142
+ pi.registerTool({
143
+ name: prefixedName,
144
+ label: prefixedName,
145
+ description,
146
+ parameters: Type.Unsafe(tool.inputSchema),
147
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
148
+ const result = await client.callTool(originalName, params);
149
+ const { content } = toTextContent(result, originalName);
150
+ return { content, details: undefined };
151
+ },
152
+ });
153
+ }
154
+ }
155
+ /** Create a VisionCaller that uses pi-ai's complete() with the model registry. */
156
+ function createPiVisionCaller(visionConfig, ctx) {
157
+ return async (instruction, imageBase64, mimeType) => {
158
+ const model = ctx.modelRegistry.find(visionConfig.provider, visionConfig.model);
159
+ if (!model) {
160
+ throw new Error(`Vision model "${visionConfig.provider}/${visionConfig.model}" not found in model registry.`);
161
+ }
162
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
163
+ if (!auth.ok) {
164
+ throw new Error(`Auth failed for vision model: ${auth.error}`);
165
+ }
166
+ const options = {
167
+ temperature: 0,
168
+ maxTokens: 2048,
169
+ };
170
+ if (auth.apiKey)
171
+ options.apiKey = auth.apiKey;
172
+ if (auth.headers)
173
+ options.headers = auth.headers;
174
+ const result = await complete(model, {
175
+ systemPrompt: VISUAL_SYSTEM_PROMPT,
176
+ messages: [
177
+ {
178
+ role: 'user',
179
+ content: [
180
+ {
181
+ type: 'text',
182
+ text: `Analyze this screenshot and respond to the following instruction:\n\n${instruction}`,
183
+ },
184
+ { type: 'image', data: imageBase64, mimeType },
185
+ ],
186
+ timestamp: Date.now(),
187
+ },
188
+ ],
189
+ }, options);
190
+ return result.content
191
+ .filter((c) => c.type === 'text')
192
+ .map((c) => c.text)
193
+ .join('');
194
+ };
195
+ }
196
+ async function registerVisionTool(visionConfig) {
197
+ pi.registerTool({
198
+ name: `${TOOL_PREFIX}analyze_screenshot`,
199
+ label: `${TOOL_PREFIX}analyze_screenshot`,
200
+ description: 'Analyze the current page visually using a screenshot. Use when you need to identify elements by visual attributes (color, layout, position) not available in the accessibility tree, or when you need precise pixel coordinates for click_at.',
201
+ parameters: Type.Object({
202
+ instruction: Type.Optional(Type.String({
203
+ description: 'What to identify or analyze visually (e.g., "Find the coordinates of the blue submit button").',
204
+ })),
205
+ }),
206
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
207
+ await ensureConnected();
208
+ const callVision = createPiVisionCaller(visionConfig, ctx);
209
+ const result = await handleAnalyzeScreenshot(client, callVision, params);
210
+ const content = [];
211
+ if (result.content) {
212
+ for (const item of result.content) {
213
+ if (item.type === 'text' && item.text) {
214
+ content.push({ type: 'text', text: item.text });
215
+ }
216
+ }
217
+ }
218
+ if (content.length === 0) {
219
+ content.push({ type: 'text', text: '' });
220
+ }
221
+ return { content, details: undefined };
222
+ },
223
+ });
224
+ }
225
+ pi.on('session_start', async () => {
226
+ await registerUpstreamTools();
227
+ if (config.visionModel) {
228
+ await registerVisionTool(config.visionModel);
229
+ }
230
+ });
231
+ pi.on('session_shutdown', async () => {
232
+ if (connected) {
233
+ await client.close();
234
+ connected = false;
235
+ }
236
+ });
237
+ }
238
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAqC,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEpF,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEjF,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EACL,uBAAuB,EACvB,oBAAoB,GAErB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAEL,YAAY,EACZ,aAAa,GAEd,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,sBAAsB,EACtB,kBAAkB,EAClB,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,CAAC;AAEvC,sGAAsG;AACtG,MAAM,WAAW,GAAG,UAAU,CAAC;AAE/B,yEAAyE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AM,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;4BACtC,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;wBAClD,CAAC;oBACH,CAAC;gBACH,CAAC;gBACD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;oBACzB,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;gBAC3C,CAAC;gBACD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;YACzC,CAAC;SACF,CAAC,CAAC;IACL,CAAC;IAED,EAAE,CAAC,EAAE,CAAC,eAAe,EAAE,KAAK,IAAI,EAAE;QAChC,MAAM,qBAAqB,EAAE,CAAC;QAC9B,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC;YACvB,MAAM,kBAAkB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,EAAE,CAAC,kBAAkB,EAAE,KAAK,IAAI,EAAE;QACnC,IAAI,SAAS,EAAE,CAAC;YACd,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;YACrB,SAAS,GAAG,KAAK,CAAC;QACpB,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,14 @@
1
+ /** Append usage hints to tool descriptions based on tool name keywords. */
2
+ export declare function augmentToolDescription(toolName: string, description: string): string;
3
+ /**
4
+ * Post-process tool output before returning to the LLM:
5
+ * - Strip embedded page snapshots (token bloat) from non-snapshot tools
6
+ * - Detect overlay/interactable issues on click actions
7
+ * - Detect stale element references
8
+ */
9
+ export declare function postProcessToolResult(toolName: string, result: string): string;
10
+ export declare function extractTextContent(content?: Array<{
11
+ type: string;
12
+ text?: string;
13
+ }>): string;
14
+ //# sourceMappingURL=tool-augment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-augment.d.ts","sourceRoot":"","sources":["../src/tool-augment.ts"],"names":[],"mappings":"AAoBA,2EAA2E;AAC3E,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAOpF;AAWD;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CA4B9E;AAED,wBAAgB,kBAAkB,CAAC,OAAO,CAAC,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,MAAM,CAM3F"}
@@ -0,0 +1,68 @@
1
+ // Extra hints appended to upstream tool descriptions.
2
+ // These steer the LLM toward correct usage (e.g. "call take_snapshot first").
3
+ const DESCRIPTION_HINTS = {
4
+ fill_form: ' Fills multiple standard HTML form fields at once. Same limitations as fill — does not work on canvas/custom widgets.',
5
+ fill: ' Fills standard HTML form fields (<input>, <textarea>, <select>) by uid. Does NOT work on custom/canvas-based widgets (e.g., Google Sheets cells, Notion blocks). If fill times out or fails, click the element first then use press_key with individual characters instead.',
6
+ click_at: ' Clicks at exact pixel coordinates (x, y). Use when you have specific coordinates for visual elements.',
7
+ click: ' Use the element uid from the accessibility tree snapshot (e.g., uid="87_4"). UIDs are invalidated after this action — call take_snapshot before using another uid.',
8
+ hover: ' Use the element uid from the accessibility tree snapshot to hover over elements.',
9
+ take_snapshot: ' Returns the accessibility tree with uid values for each element. Call this FIRST to see available elements, and AFTER every state-changing action (click, fill, press_key) before using any uid.',
10
+ navigate_page: ' Navigate to the specified URL. Call take_snapshot after to see the new page.',
11
+ new_page: ' Opens a new page/tab with the specified URL. Call take_snapshot after to see the new page.',
12
+ press_key: ' Press a SINGLE keyboard key (e.g., "Enter", "Tab", "Escape", "ArrowDown", "a", "8"). ONLY accepts one key name — do NOT pass multi-character strings like "Hello" or "A1\\nEnter". To type text, use type_text instead of calling press_key for each character.',
13
+ };
14
+ /** Append usage hints to tool descriptions based on tool name keywords. */
15
+ export function augmentToolDescription(toolName, description) {
16
+ for (const [key, hint] of Object.entries(DESCRIPTION_HINTS)) {
17
+ if (toolName.toLowerCase().includes(key)) {
18
+ return description + hint;
19
+ }
20
+ }
21
+ return description;
22
+ }
23
+ const OVERLAY_PATTERNS = [
24
+ 'not interactable',
25
+ 'obscured',
26
+ 'intercept',
27
+ 'blocked',
28
+ 'element is not visible',
29
+ 'element not found',
30
+ ];
31
+ /**
32
+ * Post-process tool output before returning to the LLM:
33
+ * - Strip embedded page snapshots (token bloat) from non-snapshot tools
34
+ * - Detect overlay/interactable issues on click actions
35
+ * - Detect stale element references
36
+ */
37
+ export function postProcessToolResult(toolName, result) {
38
+ let processed = result;
39
+ // Strip embedded snapshots to prevent token bloat (except take_snapshot)
40
+ if (toolName !== 'take_snapshot' && processed.includes('## Latest page snapshot')) {
41
+ const parts = processed.split('## Latest page snapshot');
42
+ processed = parts[0].trim();
43
+ }
44
+ // Detect overlay/interactable issues on click actions
45
+ if (toolName === 'click' || toolName.includes('click')) {
46
+ const isOverlayIssue = OVERLAY_PATTERNS.some((pattern) => processed.toLowerCase().includes(pattern));
47
+ if (isOverlayIssue) {
48
+ processed +=
49
+ '\n\nThis action may have been blocked by an overlay, popup, or tooltip. ' +
50
+ 'Look for close/dismiss buttons in the accessibility tree and click them first.';
51
+ }
52
+ }
53
+ // Detect stale element references
54
+ if (processed.toLowerCase().includes('stale') || processed.toLowerCase().includes('detached')) {
55
+ processed +=
56
+ '\n\nThe element reference is stale. Call take_snapshot to get fresh element uids.';
57
+ }
58
+ return processed;
59
+ }
60
+ export function extractTextContent(content) {
61
+ if (!content || !Array.isArray(content))
62
+ return '';
63
+ return content
64
+ .filter((c) => c.type === 'text' && c.text)
65
+ .map((c) => c.text)
66
+ .join('\n');
67
+ }
68
+ //# sourceMappingURL=tool-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,sDAAsD;IACtD,IAAI,QAAQ,KAAK,OAAO,IAAI,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;QACvD,MAAM,cAAc,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CACvD,SAAS,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,CAC1C,CAAC;QACF,IAAI,cAAc,EAAE,CAAC;YACnB,SAAS;gBACP,0EAA0E;oBAC1E,gFAAgF,CAAC;QACrF,CAAC;IACH,CAAC;IAED,kCAAkC;IAClC,IAAI,SAAS,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,SAAS,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC;QAC9F,SAAS;YACP,mFAAmF,CAAC;IACxF,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,OAAgD;IACjF,IAAI,CAAC,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;QAAE,OAAO,EAAE,CAAC;IACnD,OAAO,OAAO;SACX,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,IAAI,CAAC,CAAC,IAAI,CAAC;SAC1C,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAK,CAAC;SACnB,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@amaster.ai/pi-browser-use",
3
+ "version": "0.1.1-beta.0",
4
+ "description": "MCP proxy plugin for chrome-devtools-mcp with browser_ prefixed tools",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./package.json": {
16
+ "default": "./package.json"
17
+ }
18
+ },
19
+ "bin": {
20
+ "pi-browser-use": "./dist/cli.js"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/TGYD-helige/pi.git",
32
+ "directory": "packages/pi-browser-use"
33
+ },
34
+ "dependencies": {
35
+ "@modelcontextprotocol/sdk": "^1.29.0"
36
+ },
37
+ "peerDependencies": {
38
+ "@earendil-works/pi-ai": ">=0.74.0",
39
+ "@earendil-works/pi-coding-agent": ">=0.74.0",
40
+ "typebox": "*"
41
+ },
42
+ "devDependencies": {
43
+ "@earendil-works/pi-ai": "0.74.0",
44
+ "@earendil-works/pi-coding-agent": "0.74.0",
45
+ "tsup": "^8.4.0",
46
+ "typebox": "*",
47
+ "vitest": "^4.0.0"
48
+ },
49
+ "scripts": {
50
+ "build": "tsup",
51
+ "typecheck": "tsc -b --pretty false",
52
+ "test": "vitest run src"
53
+ }
54
+ }