btcp-browser-agent 0.1.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.
Files changed (117) hide show
  1. package/CLAUDE.md +230 -0
  2. package/LICENSE +21 -0
  3. package/README.md +309 -0
  4. package/SKILL.md +143 -0
  5. package/SNAPSHOT_IMPROVEMENTS.md +302 -0
  6. package/USAGE.md +146 -0
  7. package/dist/index.d.ts +34 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +35 -0
  10. package/dist/index.js.map +1 -0
  11. package/docs/browser-cli-design.md +500 -0
  12. package/examples/chrome-extension/CHANGELOG.md +210 -0
  13. package/examples/chrome-extension/DEBUG.md +231 -0
  14. package/examples/chrome-extension/ERROR_FIXED.md +147 -0
  15. package/examples/chrome-extension/QUICK_TEST.md +189 -0
  16. package/examples/chrome-extension/README.md +149 -0
  17. package/examples/chrome-extension/SESSION_ONLY_MODE.md +305 -0
  18. package/examples/chrome-extension/TEST_WITH_YOUR_TABS.md +97 -0
  19. package/examples/chrome-extension/build.js +43 -0
  20. package/examples/chrome-extension/manifest.json +37 -0
  21. package/examples/chrome-extension/package-lock.json +1063 -0
  22. package/examples/chrome-extension/package.json +21 -0
  23. package/examples/chrome-extension/popup.html +195 -0
  24. package/examples/chrome-extension/src/background.ts +12 -0
  25. package/examples/chrome-extension/src/content.ts +7 -0
  26. package/examples/chrome-extension/src/popup.ts +303 -0
  27. package/examples/chrome-extension/src/scenario-google-github.ts +389 -0
  28. package/examples/chrome-extension/test-page.html +127 -0
  29. package/examples/chrome-extension/tests/README.md +206 -0
  30. package/examples/chrome-extension/tests/scenario-google-to-github-star.ts +380 -0
  31. package/examples/chrome-extension/tsconfig.json +14 -0
  32. package/examples/snapshots/README.md +207 -0
  33. package/examples/snapshots/amazon-com-detail.html +9528 -0
  34. package/examples/snapshots/amazon-com-detail.snapshot.txt +997 -0
  35. package/examples/snapshots/convert-snapshots.ts +97 -0
  36. package/examples/snapshots/edition-cnn-com.html +13292 -0
  37. package/examples/snapshots/edition-cnn-com.snapshot.txt +562 -0
  38. package/examples/snapshots/github-com-microsoft-vscode.html +2916 -0
  39. package/examples/snapshots/github-com-microsoft-vscode.snapshot.txt +455 -0
  40. package/examples/snapshots/google-search.html +20012 -0
  41. package/examples/snapshots/google-search.snapshot.txt +195 -0
  42. package/examples/snapshots/metadata.json +86 -0
  43. package/examples/snapshots/npr-org-templates.html +2031 -0
  44. package/examples/snapshots/npr-org-templates.snapshot.txt +224 -0
  45. package/examples/snapshots/stackoverflow-com.html +5216 -0
  46. package/examples/snapshots/stackoverflow-com.snapshot.txt +2404 -0
  47. package/examples/snapshots/test-all-mode.html +46 -0
  48. package/examples/snapshots/test-all-mode.snapshot.txt +5 -0
  49. package/examples/snapshots/validate.test.ts +296 -0
  50. package/package.json +65 -0
  51. package/packages/cli/package.json +42 -0
  52. package/packages/cli/src/__tests__/cli.test.ts +434 -0
  53. package/packages/cli/src/__tests__/errors.test.ts +226 -0
  54. package/packages/cli/src/__tests__/executor.test.ts +275 -0
  55. package/packages/cli/src/__tests__/formatter.test.ts +260 -0
  56. package/packages/cli/src/__tests__/parser.test.ts +288 -0
  57. package/packages/cli/src/__tests__/suggestions.test.ts +255 -0
  58. package/packages/cli/src/commands/back.ts +22 -0
  59. package/packages/cli/src/commands/check.ts +33 -0
  60. package/packages/cli/src/commands/clear.ts +33 -0
  61. package/packages/cli/src/commands/click.ts +32 -0
  62. package/packages/cli/src/commands/closetab.ts +31 -0
  63. package/packages/cli/src/commands/eval.ts +41 -0
  64. package/packages/cli/src/commands/fill.ts +30 -0
  65. package/packages/cli/src/commands/focus.ts +33 -0
  66. package/packages/cli/src/commands/forward.ts +22 -0
  67. package/packages/cli/src/commands/goto.ts +34 -0
  68. package/packages/cli/src/commands/help.ts +162 -0
  69. package/packages/cli/src/commands/hover.ts +34 -0
  70. package/packages/cli/src/commands/index.ts +129 -0
  71. package/packages/cli/src/commands/newtab.ts +35 -0
  72. package/packages/cli/src/commands/press.ts +40 -0
  73. package/packages/cli/src/commands/reload.ts +25 -0
  74. package/packages/cli/src/commands/screenshot.ts +27 -0
  75. package/packages/cli/src/commands/scroll.ts +64 -0
  76. package/packages/cli/src/commands/select.ts +35 -0
  77. package/packages/cli/src/commands/snapshot.ts +21 -0
  78. package/packages/cli/src/commands/tab.ts +32 -0
  79. package/packages/cli/src/commands/tabs.ts +26 -0
  80. package/packages/cli/src/commands/text.ts +27 -0
  81. package/packages/cli/src/commands/title.ts +17 -0
  82. package/packages/cli/src/commands/type.ts +38 -0
  83. package/packages/cli/src/commands/uncheck.ts +33 -0
  84. package/packages/cli/src/commands/url.ts +17 -0
  85. package/packages/cli/src/commands/wait.ts +54 -0
  86. package/packages/cli/src/errors.ts +164 -0
  87. package/packages/cli/src/executor.ts +68 -0
  88. package/packages/cli/src/formatter.ts +215 -0
  89. package/packages/cli/src/index.ts +257 -0
  90. package/packages/cli/src/parser.ts +195 -0
  91. package/packages/cli/src/suggestions.ts +207 -0
  92. package/packages/cli/src/terminal/Terminal.ts +365 -0
  93. package/packages/cli/src/terminal/index.ts +5 -0
  94. package/packages/cli/src/types.ts +155 -0
  95. package/packages/cli/tsconfig.json +20 -0
  96. package/packages/core/package.json +35 -0
  97. package/packages/core/src/actions.ts +1210 -0
  98. package/packages/core/src/errors.ts +296 -0
  99. package/packages/core/src/index.test.ts +638 -0
  100. package/packages/core/src/index.ts +220 -0
  101. package/packages/core/src/ref-map.ts +107 -0
  102. package/packages/core/src/snapshot.ts +873 -0
  103. package/packages/core/src/types.ts +536 -0
  104. package/packages/core/tsconfig.json +23 -0
  105. package/packages/extension/README.md +129 -0
  106. package/packages/extension/package.json +43 -0
  107. package/packages/extension/src/background.ts +888 -0
  108. package/packages/extension/src/content.ts +172 -0
  109. package/packages/extension/src/index.ts +579 -0
  110. package/packages/extension/src/session-manager.ts +385 -0
  111. package/packages/extension/src/session-types.ts +144 -0
  112. package/packages/extension/src/types.ts +162 -0
  113. package/packages/extension/tsconfig.json +28 -0
  114. package/src/index.ts +64 -0
  115. package/tsconfig.build.json +12 -0
  116. package/tsconfig.json +26 -0
  117. package/vitest.config.ts +13 -0
package/CLAUDE.md ADDED
@@ -0,0 +1,230 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Project Overview
6
+
7
+ BTCP Browser Agent is a browser-native implementation for AI agents to interact with web pages. It provides a clean separation between browser-level operations (tabs, navigation, screenshots) and DOM-level operations (clicking, typing, reading elements).
8
+
9
+ ## Build Commands
10
+
11
+ ```bash
12
+ # Build all packages
13
+ npm run build
14
+
15
+ # Build individual packages (in order)
16
+ npm run build:packages
17
+
18
+ # Build Chrome extension example
19
+ cd examples/chrome-extension && npm run build
20
+
21
+ # Watch mode for extension development
22
+ cd examples/chrome-extension && npm run watch
23
+
24
+ # Clean build artifacts
25
+ npm run clean
26
+ ```
27
+
28
+ ## Testing
29
+
30
+ ```bash
31
+ # Run all tests
32
+ npm test
33
+
34
+ # Watch mode for test development
35
+ npm run test:watch
36
+
37
+ # Type checking only
38
+ npm run typecheck
39
+ ```
40
+
41
+ ## Architecture
42
+
43
+ ### Three-Layer Command Flow
44
+
45
+ Commands flow through three distinct layers:
46
+
47
+ 1. **Client Layer** (`packages/extension/src/index.ts`)
48
+ - `createClient()` provides high-level API methods
49
+ - Sends commands via `chrome.runtime.sendMessage`
50
+ - Used in popups, external scripts
51
+
52
+ 2. **Background Layer** (`packages/extension/src/background.ts`)
53
+ - `BackgroundAgent` handles browser-level operations (tabs, navigation, screenshots)
54
+ - Routes DOM commands to ContentAgent via `chrome.tabs.sendMessage`
55
+ - `SessionManager` maintains tab group state across extension lifecycle
56
+
57
+ 3. **Content Layer** (`packages/core/src/actions.ts`)
58
+ - `DOMActions` executes all DOM operations
59
+ - `createSnapshot()` generates accessibility tree with element refs
60
+ - Runs in content script context (one per tab)
61
+
62
+ ### Command Type System
63
+
64
+ Commands are strongly typed with a discriminated union:
65
+
66
+ - **CoreAction** (46 actions in `packages/core/src/types.ts`): DOM operations like `click`, `type`, `snapshot`, `highlight`
67
+ - **ExtensionAction** (11 actions in `packages/extension/src/types.ts`): Browser operations like `navigate`, `screenshot`, `tabNew`
68
+ - All commands extend `BaseCommand` with `id` and `action` fields
69
+
70
+ ### Element References and Snapshot API
71
+
72
+ The snapshot system creates stable element references:
73
+
74
+ ```typescript
75
+ // Snapshot returns a string (accessibility tree with embedded @ref:N markers)
76
+ const tree = await client.snapshot();
77
+ // Example output: "- BUTTON \"Submit\" [@ref:1]"
78
+
79
+ // Use refs in commands: { action: 'click', selector: '@ref:5' }
80
+ ```
81
+
82
+ **Important**: The snapshot API returns a `string` directly (the accessibility tree). Element refs are embedded as `@ref:N` markers in the tree and stored internally in a `RefMap` (WeakRef-based for memory management). Refs persist across commands within the same content script session and are used internally for the `highlight` feature.
83
+
84
+ ## Package Structure
85
+
86
+ ```
87
+ btcp-browser-agent/ # Monorepo root
88
+ ├── packages/
89
+ │ ├── core/ # @btcp/core - DOM operations (ContentAgent)
90
+ │ │ ├── src/actions.ts # DOMActions class - all DOM command handlers
91
+ │ │ ├── src/snapshot.ts # Accessibility tree generation
92
+ │ │ ├── src/types.ts # CoreAction types (46 actions)
93
+ │ │ └── src/ref-map.ts # Element reference management
94
+ │ │
95
+ │ ├── extension/ # @btcp/extension - Browser operations
96
+ │ │ ├── src/background.ts # BackgroundAgent (service worker)
97
+ │ │ ├── src/session-manager.ts # Tab group persistence
98
+ │ │ ├── src/content.ts # Content script setup
99
+ │ │ └── src/index.ts # Client API + types
100
+ │ │
101
+ │ └── cli/ # @btcp/cli - Command-line interface
102
+ │ ├── src/commands/ # 28 CLI command implementations
103
+ │ ├── src/parser.ts # Natural language command parser
104
+ │ └── src/executor.ts # Command execution + suggestions
105
+
106
+ └── examples/
107
+ ├── chrome-extension/ # Full extension demo (popup + background + content)
108
+ └── snapshots/ # Snapshot generation utilities
109
+ ```
110
+
111
+ ## Key Concepts
112
+
113
+ ### Highlight vs CLI Commands
114
+
115
+ The core `DOMActions` class supports `highlight` and `clearHighlight` actions, but these are NOT registered as CLI commands. To use them:
116
+
117
+ - In popup: Use `client.execute({ id: '...', action: 'highlight' })`
118
+ - NOT: `cli.execute('highlight')` (will fail with "Unknown command")
119
+
120
+ The CLI package (`packages/cli/src/commands/index.ts`) has 28 registered commands. If a core action is missing from the CLI registry, use the raw `client.execute()` method.
121
+
122
+ ### Session Management
123
+
124
+ The extension uses Chrome Tab Groups for session isolation:
125
+
126
+ - `SessionManager` persists active session to `chrome.storage.session`
127
+ - On extension reload, reconnects to stored group if it still exists
128
+ - All extension operations are scoped to the active session's tabs
129
+ - Create session: `client.groupCreate()` → returns `{ group: GroupInfo }`
130
+
131
+ ### Multi-Tab Operations
132
+
133
+ Background agent supports two patterns for multi-tab work:
134
+
135
+ ```typescript
136
+ // Pattern 1: tab() handle - interact without switching active tab
137
+ const tab = agent.tab(tabId);
138
+ await tab.snapshot();
139
+ await tab.click('@ref:5');
140
+
141
+ // Pattern 2: Pass tabId in execute options
142
+ await agent.execute(command, { tabId });
143
+ ```
144
+
145
+ Both avoid unnecessary tab switching for better performance.
146
+
147
+ ### Snapshot Formats
148
+
149
+ Snapshots support two output formats:
150
+
151
+ - `format: 'tree'` (default): Flat accessibility tree with refs
152
+ - `format: 'html'`: HTML structure with semantic xpaths
153
+
154
+ The tree format is optimized for AI consumption and includes role-based element descriptions.
155
+
156
+ ## Development Workflow
157
+
158
+ ### Working on Core Package
159
+
160
+ ```bash
161
+ # 1. Make changes in packages/core/src/
162
+ # 2. Build core package
163
+ npm run build:packages
164
+
165
+ # 3. Run tests
166
+ npm test -- packages/core
167
+
168
+ # 4. If working on extension example, rebuild it
169
+ cd examples/chrome-extension && npm run build
170
+ ```
171
+
172
+ ### Working on Extension Example
173
+
174
+ ```bash
175
+ cd examples/chrome-extension
176
+
177
+ # Watch mode - auto-rebuilds on changes
178
+ npm run watch
179
+
180
+ # Load unpacked extension in Chrome:
181
+ # 1. Open chrome://extensions
182
+ # 2. Enable "Developer mode"
183
+ # 3. Click "Load unpacked"
184
+ # 4. Select examples/chrome-extension/dist/
185
+ ```
186
+
187
+ ### Adding New Core Actions
188
+
189
+ 1. Add action type to `CoreAction` in `packages/core/src/types.ts`
190
+ 2. Create command interface extending `BaseCommand`
191
+ 3. Add case to `DOMActions.dispatch()` in `packages/core/src/actions.ts`
192
+ 4. Implement handler method in `DOMActions` class
193
+ 5. Optionally create CLI command wrapper in `packages/cli/src/commands/`
194
+
195
+ ### Adding New CLI Commands
196
+
197
+ 1. Create command file in `packages/cli/src/commands/[name].ts`
198
+ 2. Export `CommandHandler` with `name`, `description`, `execute()`, `examples`
199
+ 3. Register in `packages/cli/src/commands/index.ts`
200
+ 4. Add suggestions mapping in `packages/cli/src/suggestions.ts` if needed
201
+
202
+ ## Common Pitfalls
203
+
204
+ 1. **CLI vs Client API**: CLI commands are a subset of core actions. Use `client.execute()` for actions not in CLI registry.
205
+
206
+ 2. **Ref Lifecycle**: Element refs are cleared on navigation and only valid within the content script that created them.
207
+
208
+ 3. **Cross-Origin**: ContentAgent only works same-origin when used standalone. Extension context bypasses this via content scripts.
209
+
210
+ 4. **Build Order**: Always build packages before examples (`npm run build:packages` then `cd examples/chrome-extension && npm run build`).
211
+
212
+ 5. **Session Persistence**: Session state survives extension reload via `chrome.storage.session`, but actual tab groups can be deleted by the user.
213
+
214
+ ## Import Paths
215
+
216
+ The package exports multiple entry points:
217
+
218
+ ```typescript
219
+ // Main re-exports (convenience)
220
+ import { createContentAgent } from '@btcp/browser-agent';
221
+
222
+ // Direct package imports (preferred for clarity)
223
+ import { createContentAgent } from '@btcp/browser-agent/core';
224
+ import { BackgroundAgent, createClient } from '@btcp/browser-agent/extension';
225
+ import { createCLI } from '@btcp/browser-agent/cli';
226
+
227
+ // Extension-specific entry points
228
+ import '@btcp/browser-agent/extension/content'; // Content script setup
229
+ import '@btcp/browser-agent/extension/background'; // Background script setup
230
+ ```
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 browser-tool-calling-protocol
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,309 @@
1
+ # btcp-browser-agent
2
+
3
+ Give AI agents the power to see and control any browser.
4
+
5
+ A lightweight foundation for building AI systems that need browser access — automation, testing, web agents, or any browser-based workflow.
6
+
7
+ ## Why This Package?
8
+
9
+ AI agents struggle with browsers because:
10
+ - Raw HTML is too noisy (thousands of nodes)
11
+ - CSS selectors break when layouts change
12
+ - No stable way to reference elements across turns
13
+
14
+ **Browser Agent solves this with smart snapshots:**
15
+
16
+ ```
17
+ BUTTON "Submit" [@ref:0]
18
+ TEXTBOX "Email" [required] [@ref:1]
19
+ LINK "Forgot password?" [@ref:2]
20
+ ```
21
+
22
+ One command gives your agent a clean, semantic view of any page. Stable `@ref` markers let it interact without fragile selectors.
23
+
24
+ ## Features
25
+
26
+ - **Smart Snapshots** - Accessibility tree format optimized for AI comprehension
27
+ - **Stable Element Refs** - `@ref:N` markers that survive DOM changes within a session
28
+ - **Full Browser Control** - Navigation, tabs, screenshots, keyboard/mouse
29
+ - **46 DOM Actions** - Click, type, fill, scroll, hover, and more
30
+ - **Two Modes** - Chrome extension (full control) or standalone (same-origin)
31
+
32
+ ## Quick Example
33
+
34
+ ```typescript
35
+ import { createClient } from 'btcp-browser-agent/extension';
36
+
37
+ const agent = createClient();
38
+
39
+ // Navigate and understand the page
40
+ await agent.navigate('https://example.com');
41
+ const snapshot = await agent.snapshot();
42
+ // Returns: BUTTON "Login" [@ref:0], TEXTBOX "Email" [@ref:1], ...
43
+
44
+ // Interact using refs - no CSS selectors needed
45
+ await agent.fill('@ref:1', 'user@example.com');
46
+ await agent.click('@ref:0');
47
+ ```
48
+
49
+ ## Use Cases
50
+
51
+ - **AI Assistants** - Let LLMs browse the web and complete tasks for users
52
+ - **Browser Agents** - Foundation for autonomous web agents that research, navigate, and act
53
+ - **Automated Testing** - Reliable UI tests with stable element refs that don't break on layout changes
54
+ - **Web Automation** - Form filling, data extraction, multi-step workflow automation
55
+ - **Web Scraping** - Extract structured data with semantic understanding of page content
56
+
57
+ ## Installation
58
+
59
+ ```bash
60
+ npm install btcp-browser-agent
61
+ ```
62
+
63
+ ## Usage Modes
64
+
65
+ ### Extension Mode (Full Browser Control)
66
+
67
+ For Chrome extensions with cross-origin access, tab management, and screenshots.
68
+
69
+ **Background Script:**
70
+ ```typescript
71
+ import { BackgroundAgent, setupMessageListener } from 'btcp-browser-agent/extension';
72
+
73
+ // Option 1: Just set up message routing
74
+ setupMessageListener();
75
+
76
+ // Option 2: Use BackgroundAgent directly for programmatic control
77
+ const agent = new BackgroundAgent();
78
+ await agent.navigate('https://example.com');
79
+ await agent.screenshot();
80
+ ```
81
+
82
+ **Content Script:**
83
+ ```typescript
84
+ import { createContentAgent } from 'btcp-browser-agent';
85
+
86
+ const agent = createContentAgent();
87
+
88
+ // Take a snapshot
89
+ const { data } = await agent.execute({ id: '1', action: 'snapshot' });
90
+ console.log(data.tree); // Accessibility tree with refs
91
+
92
+ // Click an element using ref from snapshot
93
+ await agent.execute({ id: '2', action: 'click', selector: '@ref:5' });
94
+ ```
95
+
96
+ **Popup (sending commands via messaging):**
97
+ ```typescript
98
+ import { createClient } from 'btcp-browser-agent';
99
+
100
+ const client = createClient();
101
+
102
+ // Navigate and interact
103
+ await client.navigate('https://example.com');
104
+ const snapshot = await client.snapshot();
105
+ await client.click('@ref:5');
106
+ const screenshot = await client.screenshot();
107
+ ```
108
+
109
+ ### Standalone Mode (No Extension)
110
+
111
+ For use directly in a web page (limited to same-origin, no tab management):
112
+
113
+ ```typescript
114
+ import { createContentAgent } from 'btcp-browser-agent';
115
+
116
+ const agent = createContentAgent();
117
+
118
+ // Take a snapshot
119
+ const { data } = await agent.execute({ id: '1', action: 'snapshot' });
120
+
121
+ // Interact with elements
122
+ await agent.execute({ id: '2', action: 'click', selector: '@ref:5' });
123
+ await agent.execute({ id: '3', action: 'fill', selector: '@ref:3', value: 'Hello' });
124
+ ```
125
+
126
+ ## API Reference
127
+
128
+ ### BackgroundAgent (Extension Background Script)
129
+
130
+ High-level browser orchestrator that runs in the extension's background script.
131
+
132
+ ```typescript
133
+ import { BackgroundAgent } from 'btcp-browser-agent/extension';
134
+
135
+ const agent = new BackgroundAgent();
136
+
137
+ // Tab Management
138
+ await agent.newTab({ url: 'https://example.com' });
139
+ await agent.switchTab(tabId);
140
+ await agent.closeTab(tabId);
141
+ const tabs = await agent.listTabs();
142
+
143
+ // Navigation
144
+ await agent.navigate('https://example.com');
145
+ await agent.back();
146
+ await agent.forward();
147
+ await agent.reload();
148
+
149
+ // Screenshots
150
+ const screenshot = await agent.screenshot({ format: 'png' });
151
+
152
+ // Execute commands (routes to ContentAgent for DOM operations)
153
+ await agent.execute({ id: '1', action: 'click', selector: '#submit' });
154
+ ```
155
+
156
+ #### Multi-Tab Operations
157
+
158
+ ```typescript
159
+ // Open tabs
160
+ const tab1 = await agent.newTab({ url: 'https://google.com' });
161
+ const tab2 = await agent.newTab({ url: 'https://github.com', active: false });
162
+
163
+ // Method 1: tab() handle - interact without switching
164
+ const githubTab = agent.tab(tab2.id);
165
+ await githubTab.snapshot();
166
+ await githubTab.click('@ref:5');
167
+
168
+ // Method 2: Specify tabId in execute
169
+ await agent.execute(
170
+ { id: '1', action: 'getText', selector: 'h1' },
171
+ { tabId: tab2.id }
172
+ );
173
+
174
+ // Active tab stays tab1 (no switching needed)
175
+ ```
176
+
177
+ ### ContentAgent (Content Script)
178
+
179
+ DOM automation agent that runs in content scripts or web pages.
180
+
181
+ ```typescript
182
+ import { createContentAgent } from 'btcp-browser-agent';
183
+
184
+ const agent = createContentAgent();
185
+
186
+ // Execute commands
187
+ const response = await agent.execute({
188
+ id: 'cmd1',
189
+ action: 'snapshot'
190
+ });
191
+ ```
192
+
193
+ #### Available Actions
194
+
195
+ **DOM Reading:**
196
+ | Action | Description |
197
+ |--------|-------------|
198
+ | `snapshot` | Get accessibility tree with element refs |
199
+ | `getText` | Get element text content |
200
+ | `getAttribute` | Get element attribute value |
201
+ | `isVisible` | Check if element is visible |
202
+ | `isEnabled` | Check if element is enabled |
203
+ | `isChecked` | Check if checkbox/radio is checked |
204
+ | `getBoundingBox` | Get element dimensions |
205
+
206
+ **Element Interaction:**
207
+ | Action | Description |
208
+ |--------|-------------|
209
+ | `click` | Click an element |
210
+ | `dblclick` | Double-click an element |
211
+ | `type` | Type text (keystroke by keystroke) |
212
+ | `fill` | Fill input (instant) |
213
+ | `clear` | Clear input value |
214
+ | `check` | Check checkbox |
215
+ | `uncheck` | Uncheck checkbox |
216
+ | `select` | Select dropdown option |
217
+ | `hover` | Hover over element |
218
+ | `focus` | Focus element |
219
+ | `blur` | Remove focus |
220
+
221
+ **Keyboard/Mouse:**
222
+ | Action | Description |
223
+ |--------|-------------|
224
+ | `press` | Press a key |
225
+ | `keyDown` | Key down event |
226
+ | `keyUp` | Key up event |
227
+
228
+ **Other:**
229
+ | Action | Description |
230
+ |--------|-------------|
231
+ | `scroll` | Scroll page or element |
232
+ | `scrollIntoView` | Scroll element into view |
233
+ | `wait` | Wait for element state |
234
+ | `evaluate` | Execute JavaScript |
235
+
236
+ ### Element Refs
237
+
238
+ The `snapshot` action returns element references for stable selection:
239
+
240
+ ```typescript
241
+ const { data } = await agent.execute({ id: '1', action: 'snapshot' });
242
+ // data.tree: "BUTTON 'Submit' [@ref:5]\nTEXTBOX 'Email' [@ref:3]"
243
+
244
+ // Use refs in subsequent commands
245
+ await agent.execute({ id: '2', action: 'click', selector: '@ref:5' });
246
+ ```
247
+
248
+ ## Architecture
249
+
250
+ The package provides a clean separation between browser-level and DOM-level operations:
251
+
252
+ ```
253
+ ┌─────────────────────────────────────────────────────────────────┐
254
+ │ Background Script (Extension Service Worker) │
255
+ │ ┌─────────────────────────────────────────────────────────────┐│
256
+ │ │ BackgroundAgent ││
257
+ │ │ - Tab management (create, close, switch, list) ││
258
+ │ │ - Navigation (goto, back, forward, reload) ││
259
+ │ │ - Screenshots (chrome.tabs.captureVisibleTab) ││
260
+ │ │ - Routes DOM commands → ContentAgent ││
261
+ │ └─────────────────────────────────────────────────────────────┘│
262
+ └─────────────────────────────────────────────────────────────────┘
263
+
264
+ chrome.tabs.sendMessage
265
+
266
+ ┌─────────────────────────────────────────────────────────────────┐
267
+ │ Content Script (Per Tab) │
268
+ │ ┌─────────────────────────────────────────────────────────────┐│
269
+ │ │ ContentAgent ││
270
+ │ │ - DOM snapshot (accessibility tree) ││
271
+ │ │ - Element interaction (click, type, fill, hover) ││
272
+ │ │ - DOM queries (getText, getAttribute, isVisible) ││
273
+ │ │ - Keyboard/mouse events ││
274
+ │ └─────────────────────────────────────────────────────────────┘│
275
+ └─────────────────────────────────────────────────────────────────┘
276
+ ```
277
+
278
+ ## Package Structure
279
+
280
+ ```
281
+ btcp-browser-agent/
282
+ ├── @btcp/core # ContentAgent - DOM operations
283
+ │ ├── createContentAgent()
284
+ │ ├── DOMActions
285
+ │ └── createSnapshot()
286
+
287
+ ├── @btcp/extension # BackgroundAgent - Browser operations
288
+ │ ├── BackgroundAgent
289
+ │ ├── setupMessageListener()
290
+ │ └── createClient()
291
+
292
+ └── btcp-browser-agent # Main package - re-exports both
293
+ ```
294
+
295
+ ## Capabilities Comparison
296
+
297
+ | Capability | ContentAgent (Standalone) | BackgroundAgent (Extension) |
298
+ |------------|--------------------------|--------------------------|
299
+ | DOM Snapshot | Yes | Yes (via ContentAgent) |
300
+ | Element Clicks | Yes | Yes (via ContentAgent) |
301
+ | Form Filling | Yes | Yes (via ContentAgent) |
302
+ | Cross-origin | Same-origin only | Any page |
303
+ | Tab Management | No | Yes |
304
+ | Navigation | No | Yes |
305
+ | Screenshots | No | Yes |
306
+
307
+ ## License
308
+
309
+ Apache-2.0
package/SKILL.md ADDED
@@ -0,0 +1,143 @@
1
+ ---
2
+ name: agent-browser
3
+ description: Automates browser interactions for web testing, form filling, screenshots, and data extraction. Use when the user needs to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.
4
+ ---
5
+
6
+ # Browser Automation with agent-browser
7
+
8
+ ## Quick start
9
+
10
+ ```bash
11
+ agent-browser open <url> # Navigate to page
12
+ agent-browser snapshot -i # Get interactive elements with refs
13
+ agent-browser click @e1 # Click element by ref
14
+ agent-browser fill @e2 "text" # Fill input by ref
15
+ agent-browser close # Close browser
16
+ ```
17
+
18
+ ## Core workflow
19
+
20
+ 1. Navigate: `agent-browser open <url>`
21
+ 2. Snapshot: `agent-browser snapshot -i` (returns elements with refs like `@e1`, `@e2`)
22
+ 3. Interact using refs from the snapshot
23
+ 4. Re-snapshot after navigation or significant DOM changes
24
+
25
+ ## Commands
26
+
27
+ ### Navigation
28
+ ```bash
29
+ agent-browser open <url> # Navigate to URL
30
+ agent-browser back # Go back
31
+ agent-browser forward # Go forward
32
+ agent-browser reload # Reload page
33
+ agent-browser close # Close browser
34
+ ```
35
+
36
+ ### Snapshot (page analysis)
37
+ ```bash
38
+ agent-browser snapshot # Full accessibility tree
39
+ agent-browser snapshot -i # Interactive elements only (recommended)
40
+ agent-browser snapshot -c # Compact output
41
+ agent-browser snapshot -d 3 # Limit depth to 3
42
+ ```
43
+
44
+ ### Interactions (use @refs from snapshot)
45
+ ```bash
46
+ agent-browser click @e1 # Click
47
+ agent-browser dblclick @e1 # Double-click
48
+ agent-browser fill @e2 "text" # Clear and type
49
+ agent-browser type @e2 "text" # Type without clearing
50
+ agent-browser press Enter # Press key
51
+ agent-browser press Control+a # Key combination
52
+ agent-browser hover @e1 # Hover
53
+ agent-browser check @e1 # Check checkbox
54
+ agent-browser uncheck @e1 # Uncheck checkbox
55
+ agent-browser select @e1 "value" # Select dropdown
56
+ agent-browser scroll down 500 # Scroll page
57
+ agent-browser scrollintoview @e1 # Scroll element into view
58
+ ```
59
+
60
+ ### Get information
61
+ ```bash
62
+ agent-browser get text @e1 # Get element text
63
+ agent-browser get value @e1 # Get input value
64
+ agent-browser get title # Get page title
65
+ agent-browser get url # Get current URL
66
+ ```
67
+
68
+ ### Screenshots
69
+ ```bash
70
+ agent-browser screenshot # Screenshot to stdout
71
+ agent-browser screenshot path.png # Save to file
72
+ agent-browser screenshot --full # Full page
73
+ ```
74
+
75
+ ### Wait
76
+ ```bash
77
+ agent-browser wait @e1 # Wait for element
78
+ agent-browser wait 2000 # Wait milliseconds
79
+ agent-browser wait --text "Success" # Wait for text
80
+ agent-browser wait --load networkidle # Wait for network idle
81
+ ```
82
+
83
+ ### Semantic locators (alternative to refs)
84
+ ```bash
85
+ agent-browser find role button click --name "Submit"
86
+ agent-browser find text "Sign In" click
87
+ agent-browser find label "Email" fill "user@test.com"
88
+ ```
89
+
90
+ ## Example: Form submission
91
+
92
+ ```bash
93
+ agent-browser open https://example.com/form
94
+ agent-browser snapshot -i
95
+ # Output shows: textbox "Email" [ref=e1], textbox "Password" [ref=e2], button "Submit" [ref=e3]
96
+
97
+ agent-browser fill @e1 "user@example.com"
98
+ agent-browser fill @e2 "password123"
99
+ agent-browser click @e3
100
+ agent-browser wait --load networkidle
101
+ agent-browser snapshot -i # Check result
102
+ ```
103
+
104
+ ## Example: Authentication with saved state
105
+
106
+ ```bash
107
+ # Login once
108
+ agent-browser open https://app.example.com/login
109
+ agent-browser snapshot -i
110
+ agent-browser fill @e1 "username"
111
+ agent-browser fill @e2 "password"
112
+ agent-browser click @e3
113
+ agent-browser wait --url "**/dashboard"
114
+ agent-browser state save auth.json
115
+
116
+ # Later sessions: load saved state
117
+ agent-browser state load auth.json
118
+ agent-browser open https://app.example.com/dashboard
119
+ ```
120
+
121
+ ## Sessions (parallel browsers)
122
+
123
+ ```bash
124
+ agent-browser --session test1 open site-a.com
125
+ agent-browser --session test2 open site-b.com
126
+ agent-browser session list
127
+ ```
128
+
129
+ ## JSON output (for parsing)
130
+
131
+ Add `--json` for machine-readable output:
132
+ ```bash
133
+ agent-browser snapshot -i --json
134
+ agent-browser get text @e1 --json
135
+ ```
136
+
137
+ ## Debugging
138
+
139
+ ```bash
140
+ agent-browser open example.com --headed # Show browser window
141
+ agent-browser console # View console messages
142
+ agent-browser errors # View page errors
143
+ ```