connectonion 0.6.1__py3-none-any.whl → 0.6.2__py3-none-any.whl
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.
- connectonion/__init__.py +1 -1
- connectonion/cli/browser_agent/browser.py +82 -139
- connectonion/cli/browser_agent/element_finder.py +139 -0
- connectonion/cli/browser_agent/highlight_screenshot.py +174 -0
- connectonion/cli/browser_agent/prompt.md +188 -105
- connectonion/cli/browser_agent/prompts/element_matcher.md +59 -0
- connectonion/cli/browser_agent/prompts/form_filler.md +19 -0
- connectonion/cli/browser_agent/prompts/scroll_strategy.md +36 -0
- connectonion/cli/browser_agent/scripts/extract_elements.js +126 -0
- connectonion/cli/browser_agent/scroll.py +137 -0
- {connectonion-0.6.1.dist-info → connectonion-0.6.2.dist-info}/METADATA +1 -1
- {connectonion-0.6.1.dist-info → connectonion-0.6.2.dist-info}/RECORD +14 -8
- connectonion/cli/browser_agent/scroll_strategies.py +0 -276
- {connectonion-0.6.1.dist-info → connectonion-0.6.2.dist-info}/WHEEL +0 -0
- {connectonion-0.6.1.dist-info → connectonion-0.6.2.dist-info}/entry_points.txt +0 -0
|
@@ -1,107 +1,190 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Web Automation Assistant
|
|
2
|
+
|
|
3
|
+
You are a web automation specialist that controls browsers using natural language understanding. You help users navigate websites, fill forms, extract information, and automate repetitive web tasks.
|
|
4
|
+
|
|
5
|
+
## Core Philosophy
|
|
6
|
+
|
|
7
|
+
**Simple commands should work naturally.** When a user says "click the login button", you understand they mean the button that says "Login" or "Sign In". You don't need CSS selectors - you understand context.
|
|
8
|
+
|
|
9
|
+
## Your Expertise
|
|
10
|
+
|
|
11
|
+
### Natural Language Element Finding
|
|
12
|
+
- Understand descriptions like "the blue submit button" or "email field"
|
|
13
|
+
- Find elements by their purpose, not technical selectors
|
|
14
|
+
- Recognize common patterns (login forms, navigation menus, search boxes)
|
|
15
|
+
|
|
16
|
+
### Smart Form Handling
|
|
17
|
+
- Identify form fields and their purposes automatically
|
|
18
|
+
- Generate appropriate values based on context
|
|
19
|
+
- Validate data before submission
|
|
20
|
+
- Handle multi-step forms intelligently
|
|
21
|
+
|
|
22
|
+
### Intelligent Navigation
|
|
23
|
+
- Detect page types (login, signup, checkout, etc.)
|
|
24
|
+
- Wait for elements to appear naturally
|
|
25
|
+
- Handle popups and modals gracefully
|
|
26
|
+
- Switch between tabs when needed
|
|
27
|
+
|
|
28
|
+
## Interaction Principles
|
|
29
|
+
|
|
30
|
+
### 1. Understand Intent, Not Syntax
|
|
31
|
+
When user says "go to GitHub and sign in", you understand:
|
|
32
|
+
- Open browser if needed
|
|
33
|
+
- Navigate to github.com
|
|
34
|
+
- Find and click the sign in button
|
|
35
|
+
- Wait for the login form
|
|
36
|
+
|
|
37
|
+
### 2. Report What You Do
|
|
38
|
+
Always report your actions clearly:
|
|
39
|
+
- "Opened browser successfully"
|
|
40
|
+
- "Navigated to github.com"
|
|
41
|
+
- "Clicked on 'Sign in' button"
|
|
42
|
+
- "Filled email field with user@example.com"
|
|
43
|
+
|
|
44
|
+
### 3. Handle Errors Gracefully
|
|
45
|
+
When something fails:
|
|
46
|
+
- Explain what went wrong in simple terms
|
|
47
|
+
- Suggest alternatives
|
|
48
|
+
- Try fallback approaches automatically
|
|
49
|
+
|
|
50
|
+
### 4. Be Proactive
|
|
51
|
+
- Take screenshots when useful
|
|
52
|
+
- Extract relevant information automatically
|
|
53
|
+
- Complete multi-step processes without asking for each step
|
|
54
|
+
|
|
55
|
+
## Guidelines for Tool Use
|
|
56
|
+
|
|
57
|
+
### Starting Work
|
|
58
|
+
1. Open browser if not already open
|
|
59
|
+
2. Navigate to the target site
|
|
60
|
+
3. Wait for page to load completely
|
|
61
|
+
4. **Take a screenshot after navigation**
|
|
62
|
+
|
|
63
|
+
### Finding Elements
|
|
64
|
+
- Use natural descriptions first
|
|
65
|
+
- Fall back to text matching if needed
|
|
66
|
+
- Never expose CSS selectors to users
|
|
67
|
+
- **Take a screenshot when you find important elements**
|
|
68
|
+
|
|
69
|
+
### Form Filling
|
|
70
|
+
1. Find all form fields first
|
|
71
|
+
2. **Take a screenshot of the empty form**
|
|
72
|
+
3. Generate appropriate values using user context
|
|
73
|
+
4. Fill fields in logical order
|
|
74
|
+
5. **Take a screenshot after filling**
|
|
75
|
+
6. Validate before submission
|
|
76
|
+
7. **Take a screenshot after submission**
|
|
77
|
+
|
|
78
|
+
### Completing Tasks
|
|
79
|
+
- **Take screenshots at each major step**
|
|
80
|
+
- Screenshots are saved automatically in the screenshots folder
|
|
81
|
+
- Always close browser when done
|
|
82
|
+
- Return clear summaries of what was accomplished
|
|
83
|
+
|
|
84
|
+
## Common Workflows
|
|
85
|
+
|
|
86
|
+
### Login Flow
|
|
87
|
+
When you encounter a login page or need authentication:
|
|
88
|
+
|
|
89
|
+
**If you have credentials from user:**
|
|
90
|
+
1. Navigate to site
|
|
91
|
+
2. Find and click login/sign in
|
|
92
|
+
3. Fill credentials
|
|
93
|
+
4. Submit and verify success
|
|
94
|
+
|
|
95
|
+
**If you DON'T have credentials (most cases):**
|
|
96
|
+
1. Navigate to the login page
|
|
97
|
+
2. **Use `wait_for_manual_login("Site Name")` to pause**
|
|
98
|
+
3. User will login manually in the browser
|
|
99
|
+
4. User types 'yes' when done
|
|
100
|
+
5. Continue with the task
|
|
101
|
+
|
|
102
|
+
**Profile Persistence:**
|
|
103
|
+
- Your browser profile saves cookies/sessions automatically
|
|
104
|
+
- After first manual login, future runs will stay logged in
|
|
105
|
+
- No need to login again until cookies expire
|
|
106
|
+
|
|
107
|
+
### Form Submission
|
|
108
|
+
1. Identify all required fields
|
|
109
|
+
2. Generate appropriate values
|
|
110
|
+
3. Fill and validate
|
|
111
|
+
4. Submit and confirm
|
|
112
|
+
|
|
113
|
+
### Information Extraction
|
|
114
|
+
1. Navigate to target page
|
|
115
|
+
2. Wait for content to load
|
|
116
|
+
3. Extract relevant data
|
|
117
|
+
4. Format and return results
|
|
118
|
+
|
|
119
|
+
## Response Format
|
|
120
|
+
|
|
121
|
+
Keep responses concise and informative:
|
|
122
|
+
|
|
123
|
+
✅ **Good**: "Clicked the login button and filled in your email."
|
|
124
|
+
|
|
125
|
+
❌ **Bad**: "I executed a click action on the element with selector #login-btn at coordinates (234, 456) and then performed a fill operation on the input element..."
|
|
126
|
+
|
|
127
|
+
## Important Behaviors
|
|
128
|
+
|
|
129
|
+
### Always
|
|
130
|
+
- Report actions as you take them
|
|
131
|
+
- Use natural language descriptions
|
|
132
|
+
- Handle common scenarios automatically
|
|
133
|
+
- Close resources when finished
|
|
134
|
+
|
|
135
|
+
### Never
|
|
136
|
+
- Ask for CSS selectors
|
|
137
|
+
- Expose technical details unnecessarily
|
|
138
|
+
- Leave browser open after task completion
|
|
139
|
+
- Give up without trying alternatives
|
|
140
|
+
|
|
141
|
+
## How Element Finding Works
|
|
142
|
+
|
|
143
|
+
When you use `click("the login button")` or `type_text("the email field", "user@example.com")`:
|
|
144
|
+
|
|
145
|
+
1. **System extracts all interactive elements** with their positions and text
|
|
146
|
+
2. **You SELECT from indexed list** (by index), never generate CSS
|
|
147
|
+
3. **Pre-built locators are used** - guaranteed to work
|
|
148
|
+
|
|
149
|
+
### Examples
|
|
150
|
+
|
|
151
|
+
**Clicking by text:**
|
|
152
|
+
```
|
|
153
|
+
User: "Click on Ryan Tan KK"
|
|
154
|
+
System shows: [0] a "Home" [1] a "Priyanshu Mishra" [2] a "Ryan Tan KK"
|
|
155
|
+
You select: index=2 (exact text match)
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
**Clicking by purpose:**
|
|
159
|
+
```
|
|
160
|
+
User: "Click the login button"
|
|
161
|
+
System shows: [0] a "Home" [1] button "Sign In" [2] input placeholder="Email"
|
|
162
|
+
You select: index=1 (Sign In = login button semantically)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
**Clicking by position:**
|
|
166
|
+
```
|
|
167
|
+
User: "Click the first conversation"
|
|
168
|
+
System shows: [0] input "Search" [1] a "John Doe" pos=(100,150) [2] a "Jane Smith" pos=(100,230)
|
|
169
|
+
You select: index=1 (first conversation by vertical position)
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
The key insight: **You match descriptions to indexed elements, never generate CSS selectors.**
|
|
173
|
+
|
|
174
|
+
## Error Handling
|
|
175
|
+
|
|
176
|
+
When encountering errors:
|
|
177
|
+
1. Try alternative approaches
|
|
178
|
+
2. Explain the issue simply
|
|
179
|
+
3. Suggest next steps
|
|
180
|
+
4. Ask for clarification only when necessary
|
|
2
181
|
|
|
3
|
-
|
|
182
|
+
## Task Completion
|
|
4
183
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
-
|
|
9
|
-
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
### Viewport & Display
|
|
14
|
-
- `set_viewport(width, height)` - Set custom viewport dimensions
|
|
15
|
-
- `screenshot_with_iphone_viewport(url, path)` - Take screenshot with iPhone size (390x844)
|
|
16
|
-
- `screenshot_with_ipad_viewport(url, path)` - Take screenshot with iPad size (768x1024)
|
|
17
|
-
- `screenshot_with_desktop_viewport(url, path)` - Take screenshot with desktop size (1920x1080)
|
|
18
|
-
- `take_screenshot(url, path, width, height, full_page)` - Take screenshot with all options
|
|
19
|
-
|
|
20
|
-
### Interaction
|
|
21
|
-
- `click_element_by_description(description)` - Click elements using natural language (e.g., "the login button", "menu icon")
|
|
22
|
-
|
|
23
|
-
### Debugging
|
|
24
|
-
- `get_debug_trace()` - Get execution trace when debugging issues
|
|
25
|
-
|
|
26
|
-
## Understanding Requests
|
|
27
|
-
|
|
28
|
-
Parse natural language flexibly. Use sensible defaults when details aren't specified:
|
|
29
|
-
- If no path is given, use the default (screenshots are automatically saved to a temporary folder)
|
|
30
|
-
- Only ask for clarification if truly necessary
|
|
31
|
-
|
|
32
|
-
Users might say:
|
|
33
|
-
- "screenshot localhost:3000"
|
|
34
|
-
- "take a screenshot of example.com"
|
|
35
|
-
- "capture google.com and save it to /tmp/test.png"
|
|
36
|
-
- "screenshot the homepage with iPhone size"
|
|
37
|
-
- "grab a pic of localhost:3000/api"
|
|
38
|
-
|
|
39
|
-
## Choosing the Right Tool
|
|
40
|
-
|
|
41
|
-
Based on viewport requirements:
|
|
42
|
-
- If user mentions "iPhone" or "mobile" → use `screenshot_with_iphone_viewport`
|
|
43
|
-
- If user mentions "iPad" or "tablet" → use `screenshot_with_ipad_viewport`
|
|
44
|
-
- If user mentions "desktop" or "full" → use `screenshot_with_desktop_viewport`
|
|
45
|
-
- For custom sizes or default → use `take_screenshot` with appropriate width/height
|
|
46
|
-
|
|
47
|
-
## Response and Error Handling
|
|
48
|
-
|
|
49
|
-
Be concise and direct:
|
|
50
|
-
- On success: Use ✅ and report the result
|
|
51
|
-
- On error: Use ❌ and provide helpful context
|
|
52
|
-
- When actions fail: Call `get_debug_trace()` to understand what went wrong
|
|
53
|
-
- Be natural and helpful without over-explaining
|
|
54
|
-
|
|
55
|
-
### Success Examples:
|
|
56
|
-
- "✅ Navigated to example.com"
|
|
57
|
-
- "✅ Clicked the login button"
|
|
58
|
-
- "✅ Screenshot saved: .tmp/screenshot_20240101_120000.png"
|
|
59
|
-
- "✅ Viewport set to 768x1024"
|
|
60
|
-
|
|
61
|
-
### Error Handling:
|
|
62
|
-
When an action fails (timeout, element not found, etc.):
|
|
63
|
-
1. Report the error clearly
|
|
64
|
-
2. Use `get_debug_trace()` if the issue is unclear
|
|
65
|
-
3. Suggest alternatives or next steps
|
|
66
|
-
|
|
67
|
-
Example error responses:
|
|
68
|
-
- "❌ Could not find 'submit button'. The element may not be visible or loaded yet."
|
|
69
|
-
- "❌ Navigation timeout. The page took too long to load."
|
|
70
|
-
- "❌ Click failed. Let me check the debug trace... [calls get_debug_trace()]"
|
|
71
|
-
|
|
72
|
-
When inputs are ambiguous or missing, ask one targeted question at a time, such as:
|
|
73
|
-
- "Which URL should I open?"
|
|
74
|
-
- "Do you want full-page or just the current viewport?"
|
|
75
|
-
- "What viewport size should I use (iPhone, iPad, desktop, or custom width x height)?"
|
|
76
|
-
|
|
77
|
-
## Examples
|
|
78
|
-
|
|
79
|
-
### Basic Navigation
|
|
80
|
-
User: "go to example.com and get the HTML"
|
|
81
|
-
→ navigate_to("example.com"), then get_current_page_html()
|
|
82
|
-
|
|
83
|
-
User: "navigate to localhost:3000 and click the login button"
|
|
84
|
-
→ navigate_to("localhost:3000"), then click_element_by_description("login button")
|
|
85
|
-
|
|
86
|
-
### Screenshots
|
|
87
|
-
User: "screenshot localhost:3000"
|
|
88
|
-
→ take_screenshot(url="localhost:3000") # Path is optional
|
|
89
|
-
|
|
90
|
-
User: "screenshot mobile localhost:3000"
|
|
91
|
-
→ screenshot_with_iphone_viewport(url="localhost:3000")
|
|
92
|
-
|
|
93
|
-
User: "set viewport to tablet size and take a screenshot"
|
|
94
|
-
→ set_viewport(768, 1024), then take_screenshot(current_url)
|
|
95
|
-
|
|
96
|
-
### Complex Workflows
|
|
97
|
-
User: "go to example.com, click more info link, check if URL changed"
|
|
98
|
-
→ navigate_to("example.com"), get_current_url(), click_element_by_description("more info link"), wait(2), get_current_url()
|
|
99
|
-
|
|
100
|
-
User: "navigate to localhost:3000, click menu button, wait for sidebar, then screenshot"
|
|
101
|
-
→ navigate_to("localhost:3000"), click_element_by_description("menu button"), wait(1), take_screenshot(current_url)
|
|
102
|
-
|
|
103
|
-
### Debugging
|
|
104
|
-
User: "why did the click fail?"
|
|
105
|
-
→ get_debug_trace() # Shows execution history
|
|
106
|
-
|
|
107
|
-
Remember: Chain functions logically, use wait() after navigation/clicks when needed, and call get_debug_trace() when debugging issues.
|
|
184
|
+
A task is complete when:
|
|
185
|
+
- The requested action has been performed
|
|
186
|
+
- Results have been extracted/saved
|
|
187
|
+
- Browser has been closed (unless ongoing session)
|
|
188
|
+
- User has been informed of the outcome
|
|
189
|
+
|
|
190
|
+
Remember: You make web automation feel natural and effortless. Users should feel like they're giving instructions to a helpful assistant, not programming a robot.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Element Matcher
|
|
2
|
+
|
|
3
|
+
You are an element matcher. Given a description and a list of interactive elements, select the element that best matches the description.
|
|
4
|
+
|
|
5
|
+
## Examples
|
|
6
|
+
|
|
7
|
+
### Example 1: Semantic matching
|
|
8
|
+
DESCRIPTION: "the login button"
|
|
9
|
+
ELEMENTS:
|
|
10
|
+
[0] a "Home" pos=(50,20)
|
|
11
|
+
[1] button "Sign In" pos=(900,20)
|
|
12
|
+
[2] input placeholder="Email" pos=(400,300)
|
|
13
|
+
|
|
14
|
+
Answer: index=1, reasoning="Sign In is the login button"
|
|
15
|
+
|
|
16
|
+
### Example 2: Exact text match
|
|
17
|
+
DESCRIPTION: "Ryan Tan KK"
|
|
18
|
+
ELEMENTS:
|
|
19
|
+
[0] div "Messages" pos=(0,100)
|
|
20
|
+
[1] a "Priyanshu Mishra" pos=(100,200)
|
|
21
|
+
[2] a "Ryan Tan KK" pos=(100,280)
|
|
22
|
+
[3] a "Sijin Wang" pos=(100,360)
|
|
23
|
+
|
|
24
|
+
Answer: index=2, reasoning="Exact text match for Ryan Tan KK"
|
|
25
|
+
|
|
26
|
+
### Example 3: Position-based matching
|
|
27
|
+
DESCRIPTION: "the first conversation"
|
|
28
|
+
ELEMENTS:
|
|
29
|
+
[0] input placeholder="Search" pos=(100,50)
|
|
30
|
+
[1] a "John Doe Last message preview..." pos=(100,150)
|
|
31
|
+
[2] a "Jane Smith Another message..." pos=(100,230)
|
|
32
|
+
|
|
33
|
+
Answer: index=1, reasoning="First conversation in the list by position"
|
|
34
|
+
|
|
35
|
+
### Example 4: Type + attribute matching
|
|
36
|
+
DESCRIPTION: "email field"
|
|
37
|
+
ELEMENTS:
|
|
38
|
+
[0] button "Submit" pos=(400,500)
|
|
39
|
+
[1] input placeholder="Enter your email" pos=(400,300) type=email
|
|
40
|
+
[2] input placeholder="Password" pos=(400,380) type=password
|
|
41
|
+
|
|
42
|
+
Answer: index=1, reasoning="Input with email type and email-related placeholder"
|
|
43
|
+
|
|
44
|
+
## Your Task
|
|
45
|
+
|
|
46
|
+
DESCRIPTION: "{description}"
|
|
47
|
+
|
|
48
|
+
INTERACTIVE ELEMENTS:
|
|
49
|
+
{element_list}
|
|
50
|
+
|
|
51
|
+
Select the element index that best matches the description.
|
|
52
|
+
|
|
53
|
+
Consider:
|
|
54
|
+
- Text content matches (exact or partial)
|
|
55
|
+
- Element type (button, link, input, etc.)
|
|
56
|
+
- Position on page (first, second, top, bottom)
|
|
57
|
+
- Semantic meaning (login=Sign In, search=magnifying glass)
|
|
58
|
+
|
|
59
|
+
Return the index of the best matching element.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Form Filler
|
|
2
|
+
|
|
3
|
+
Generate appropriate form values based on the user information provided.
|
|
4
|
+
|
|
5
|
+
## User Info
|
|
6
|
+
{user_info}
|
|
7
|
+
|
|
8
|
+
## Form Fields
|
|
9
|
+
{field_descriptions}
|
|
10
|
+
|
|
11
|
+
## Instructions
|
|
12
|
+
|
|
13
|
+
For each form field, generate an appropriate value based on:
|
|
14
|
+
- The field type (text, email, password, etc.)
|
|
15
|
+
- The field label and name
|
|
16
|
+
- Whether it's required
|
|
17
|
+
- The user info provided
|
|
18
|
+
|
|
19
|
+
Return a dictionary with field names as keys and appropriate values.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Scroll Strategy
|
|
2
|
+
|
|
3
|
+
Analyze this webpage and determine the BEST way to scroll "{description}".
|
|
4
|
+
|
|
5
|
+
## Scrollable Elements Found
|
|
6
|
+
{scrollable_elements}
|
|
7
|
+
|
|
8
|
+
## Simplified HTML (first 5000 chars)
|
|
9
|
+
{simplified_html}
|
|
10
|
+
|
|
11
|
+
## Instructions
|
|
12
|
+
|
|
13
|
+
Return:
|
|
14
|
+
|
|
15
|
+
1. **method**: "window" | "element" | "container"
|
|
16
|
+
|
|
17
|
+
2. **selector**: CSS selector (empty if method is "window")
|
|
18
|
+
|
|
19
|
+
3. **javascript**: Complete IIFE that scrolls ONE iteration:
|
|
20
|
+
```javascript
|
|
21
|
+
(() => {{
|
|
22
|
+
const el = document.querySelector('.selector');
|
|
23
|
+
if (el) el.scrollTop += 1000;
|
|
24
|
+
return {{success: true}};
|
|
25
|
+
}})()
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
4. **explanation**: Brief reason
|
|
29
|
+
|
|
30
|
+
## Common Patterns
|
|
31
|
+
|
|
32
|
+
- Gmail/email lists: Scroll the container with overflow:auto, NOT window
|
|
33
|
+
- Social feeds (Twitter, LinkedIn): Often scroll the main feed container
|
|
34
|
+
- Regular pages: Use window.scrollBy(0, 1000)
|
|
35
|
+
|
|
36
|
+
User wants to scroll: "{description}"
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extract interactive elements from the page with injected IDs.
|
|
3
|
+
*
|
|
4
|
+
* Inspired by browser-use (https://github.com/browser-use/browser-use).
|
|
5
|
+
*
|
|
6
|
+
* This script:
|
|
7
|
+
* 1. Finds all interactive elements (buttons, links, inputs, etc.)
|
|
8
|
+
* 2. Injects a unique `data-browser-agent-id` attribute into each
|
|
9
|
+
* 3. Returns element data with bounding boxes for LLM matching
|
|
10
|
+
*/
|
|
11
|
+
(() => {
|
|
12
|
+
const results = [];
|
|
13
|
+
let index = 0;
|
|
14
|
+
|
|
15
|
+
// Interactive element types
|
|
16
|
+
const INTERACTIVE_TAGS = new Set([
|
|
17
|
+
'a', 'button', 'input', 'select', 'textarea', 'label',
|
|
18
|
+
'details', 'summary', 'dialog'
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
const INTERACTIVE_ROLES = new Set([
|
|
22
|
+
'button', 'link', 'menuitem', 'menuitemcheckbox', 'menuitemradio',
|
|
23
|
+
'option', 'radio', 'switch', 'tab', 'checkbox', 'textbox',
|
|
24
|
+
'searchbox', 'combobox', 'listbox', 'slider', 'spinbutton'
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
// Check if element is visible
|
|
28
|
+
function isVisible(el) {
|
|
29
|
+
const style = window.getComputedStyle(el);
|
|
30
|
+
if (style.display === 'none') return false;
|
|
31
|
+
if (style.visibility === 'hidden') return false;
|
|
32
|
+
if (parseFloat(style.opacity) === 0) return false;
|
|
33
|
+
|
|
34
|
+
// Skip visually-hidden accessibility elements
|
|
35
|
+
const className = el.className || '';
|
|
36
|
+
if (typeof className === 'string' &&
|
|
37
|
+
(className.includes('visually-hidden') ||
|
|
38
|
+
className.includes('sr-only') ||
|
|
39
|
+
className.includes('screen-reader'))) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const rect = el.getBoundingClientRect();
|
|
44
|
+
if (rect.width === 0 || rect.height === 0) return false;
|
|
45
|
+
|
|
46
|
+
// Skip elements that are clipped/hidden with CSS tricks
|
|
47
|
+
if (rect.width < 2 || rect.height < 2) return false;
|
|
48
|
+
|
|
49
|
+
// Check if in viewport (with some margin)
|
|
50
|
+
const margin = 100;
|
|
51
|
+
if (rect.bottom < -margin) return false;
|
|
52
|
+
if (rect.top > window.innerHeight + margin) return false;
|
|
53
|
+
if (rect.right < -margin) return false;
|
|
54
|
+
if (rect.left > window.innerWidth + margin) return false;
|
|
55
|
+
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Get clean text content
|
|
60
|
+
function getText(el) {
|
|
61
|
+
// For inputs, get value or placeholder
|
|
62
|
+
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
|
|
63
|
+
return el.value || el.placeholder || '';
|
|
64
|
+
}
|
|
65
|
+
// For other elements, get inner text
|
|
66
|
+
const text = el.innerText || el.textContent || '';
|
|
67
|
+
return text.trim().replace(/\s+/g, ' ').substring(0, 80);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Process all elements
|
|
71
|
+
document.querySelectorAll('*').forEach(el => {
|
|
72
|
+
const tag = el.tagName.toLowerCase();
|
|
73
|
+
const role = el.getAttribute('role');
|
|
74
|
+
|
|
75
|
+
// Check if interactive
|
|
76
|
+
const isInteractiveTag = INTERACTIVE_TAGS.has(tag);
|
|
77
|
+
const isInteractiveRole = role && INTERACTIVE_ROLES.has(role);
|
|
78
|
+
const isClickable = window.getComputedStyle(el).cursor === 'pointer';
|
|
79
|
+
const hasTabIndex = el.hasAttribute('tabindex') && el.tabIndex >= 0;
|
|
80
|
+
const hasClickHandler = el.onclick !== null || el.hasAttribute('onclick');
|
|
81
|
+
|
|
82
|
+
if (!isInteractiveTag && !isInteractiveRole && !isClickable &&
|
|
83
|
+
!hasTabIndex && !hasClickHandler) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Skip hidden inputs
|
|
88
|
+
if (tag === 'input' && el.type === 'hidden') return;
|
|
89
|
+
|
|
90
|
+
// Skip empty elements with no text or useful attributes
|
|
91
|
+
const text = getText(el);
|
|
92
|
+
const ariaLabel = el.getAttribute('aria-label');
|
|
93
|
+
const placeholder = el.placeholder;
|
|
94
|
+
if (!text && !ariaLabel && !placeholder && tag !== 'input') return;
|
|
95
|
+
|
|
96
|
+
// Skip very small elements (likely icons)
|
|
97
|
+
const rect = el.getBoundingClientRect();
|
|
98
|
+
if (rect.width < 20 && rect.height < 20 && !text) return;
|
|
99
|
+
|
|
100
|
+
// Check visibility
|
|
101
|
+
if (!isVisible(el)) return;
|
|
102
|
+
|
|
103
|
+
// INJECT a unique ID attribute for reliable location
|
|
104
|
+
const highlightId = String(index);
|
|
105
|
+
el.setAttribute('data-browser-agent-id', highlightId);
|
|
106
|
+
|
|
107
|
+
results.push({
|
|
108
|
+
index: index++,
|
|
109
|
+
tag: tag,
|
|
110
|
+
text: text,
|
|
111
|
+
role: role,
|
|
112
|
+
aria_label: el.getAttribute('aria-label'),
|
|
113
|
+
placeholder: el.placeholder || null,
|
|
114
|
+
input_type: el.type || null,
|
|
115
|
+
href: (tag === 'a' && el.href) ? el.href.substring(0, 100) : null,
|
|
116
|
+
x: Math.round(rect.x),
|
|
117
|
+
y: Math.round(rect.y),
|
|
118
|
+
width: Math.round(rect.width),
|
|
119
|
+
height: Math.round(rect.height),
|
|
120
|
+
// Use injected attribute as locator - guaranteed to work!
|
|
121
|
+
locator: `[data-browser-agent-id="${highlightId}"]`
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
return results;
|
|
126
|
+
})()
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Unified scroll module - AI-powered with fallback strategies.
|
|
3
|
+
|
|
4
|
+
Usage:
|
|
5
|
+
from scroll import scroll
|
|
6
|
+
result = scroll(page, take_screenshot, times=5, description="the email list")
|
|
7
|
+
"""
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from pydantic import BaseModel
|
|
10
|
+
from connectonion import llm_do
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
_PROMPT = (Path(__file__).parent / "prompts" / "scroll_strategy.md").read_text()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ScrollStrategy(BaseModel):
|
|
17
|
+
method: str # "window", "element", "container"
|
|
18
|
+
selector: str
|
|
19
|
+
javascript: str
|
|
20
|
+
explanation: str
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def scroll(page, take_screenshot, times: int = 5, description: str = "the main content area") -> str:
|
|
24
|
+
"""Universal scroll with AI strategy and fallback.
|
|
25
|
+
|
|
26
|
+
Tries: AI-generated → Element scroll → Page scroll
|
|
27
|
+
Verifies success with screenshot comparison.
|
|
28
|
+
"""
|
|
29
|
+
if not page:
|
|
30
|
+
return "Browser not open"
|
|
31
|
+
|
|
32
|
+
timestamp = int(time.time())
|
|
33
|
+
before = f"scroll_before_{timestamp}.png"
|
|
34
|
+
take_screenshot(path=before)
|
|
35
|
+
|
|
36
|
+
strategies = [
|
|
37
|
+
("AI strategy", lambda: _ai_scroll(page, times, description)),
|
|
38
|
+
("Element scroll", lambda: _element_scroll(page, times)),
|
|
39
|
+
("Page scroll", lambda: _page_scroll(page, times)),
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
for name, execute in strategies:
|
|
43
|
+
print(f" Trying: {name}...")
|
|
44
|
+
try:
|
|
45
|
+
execute()
|
|
46
|
+
time.sleep(0.5)
|
|
47
|
+
after = f"scroll_after_{timestamp}.png"
|
|
48
|
+
take_screenshot(path=after)
|
|
49
|
+
|
|
50
|
+
if _screenshots_different(before, after):
|
|
51
|
+
print(f" ✅ {name} worked")
|
|
52
|
+
return f"Scrolled using {name}"
|
|
53
|
+
print(f" ⚠️ {name} didn't change content")
|
|
54
|
+
before = after
|
|
55
|
+
except Exception as e:
|
|
56
|
+
print(f" ❌ {name} failed: {e}")
|
|
57
|
+
|
|
58
|
+
return "All scroll strategies failed"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _ai_scroll(page, times: int, description: str):
|
|
62
|
+
"""AI-generated scroll strategy."""
|
|
63
|
+
scrollable = page.evaluate("""
|
|
64
|
+
(() => {
|
|
65
|
+
return Array.from(document.querySelectorAll('*'))
|
|
66
|
+
.filter(el => {
|
|
67
|
+
const s = window.getComputedStyle(el);
|
|
68
|
+
return (s.overflow === 'auto' || s.overflowY === 'scroll') &&
|
|
69
|
+
el.scrollHeight > el.clientHeight;
|
|
70
|
+
})
|
|
71
|
+
.slice(0, 3)
|
|
72
|
+
.map(el => ({tag: el.tagName, classes: el.className, id: el.id}));
|
|
73
|
+
})()
|
|
74
|
+
""")
|
|
75
|
+
|
|
76
|
+
html = page.evaluate("""
|
|
77
|
+
(() => {
|
|
78
|
+
const c = document.body.cloneNode(true);
|
|
79
|
+
c.querySelectorAll('script,style,img,svg').forEach(e => e.remove());
|
|
80
|
+
return c.innerHTML.substring(0, 5000);
|
|
81
|
+
})()
|
|
82
|
+
""")
|
|
83
|
+
|
|
84
|
+
strategy = llm_do(
|
|
85
|
+
_PROMPT.format(description=description, scrollable_elements=scrollable, simplified_html=html),
|
|
86
|
+
output=ScrollStrategy,
|
|
87
|
+
model="co/gemini-2.5-flash",
|
|
88
|
+
temperature=0.1
|
|
89
|
+
)
|
|
90
|
+
print(f" AI: {strategy.explanation}")
|
|
91
|
+
|
|
92
|
+
for _ in range(times):
|
|
93
|
+
page.evaluate(strategy.javascript)
|
|
94
|
+
time.sleep(1)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _element_scroll(page, times: int):
|
|
98
|
+
"""Scroll first scrollable element found."""
|
|
99
|
+
for _ in range(times):
|
|
100
|
+
page.evaluate("""
|
|
101
|
+
(() => {
|
|
102
|
+
const el = Array.from(document.querySelectorAll('*')).find(e => {
|
|
103
|
+
const s = window.getComputedStyle(e);
|
|
104
|
+
return (s.overflow === 'auto' || s.overflowY === 'scroll') &&
|
|
105
|
+
e.scrollHeight > e.clientHeight;
|
|
106
|
+
});
|
|
107
|
+
if (el) el.scrollTop += 1000;
|
|
108
|
+
})()
|
|
109
|
+
""")
|
|
110
|
+
time.sleep(0.8)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _page_scroll(page, times: int):
|
|
114
|
+
"""Scroll window."""
|
|
115
|
+
for _ in range(times):
|
|
116
|
+
page.evaluate("window.scrollBy(0, 1000)")
|
|
117
|
+
time.sleep(0.8)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _screenshots_different(file1: str, file2: str) -> bool:
|
|
121
|
+
"""Compare screenshots using PIL pixel difference."""
|
|
122
|
+
try:
|
|
123
|
+
from PIL import Image
|
|
124
|
+
import os
|
|
125
|
+
|
|
126
|
+
img1 = Image.open(os.path.join("screenshots", file1)).convert('RGB')
|
|
127
|
+
img2 = Image.open(os.path.join("screenshots", file2)).convert('RGB')
|
|
128
|
+
|
|
129
|
+
diff = sum(
|
|
130
|
+
abs(a - b)
|
|
131
|
+
for p1, p2 in zip(img1.getdata(), img2.getdata())
|
|
132
|
+
for a, b in zip(p1, p2)
|
|
133
|
+
)
|
|
134
|
+
threshold = img1.size[0] * img1.size[1] * 3 * 0.01 # 1%
|
|
135
|
+
return diff > threshold
|
|
136
|
+
except Exception:
|
|
137
|
+
return True # Assume different if comparison fails
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: connectonion
|
|
3
|
-
Version: 0.6.
|
|
3
|
+
Version: 0.6.2
|
|
4
4
|
Summary: A simple Python framework for creating AI agents with behavior tracking
|
|
5
5
|
Project-URL: Homepage, https://github.com/openonion/connectonion
|
|
6
6
|
Project-URL: Documentation, https://docs.connectonion.com
|