| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 1 | // Package browse provides browser automation tools for the agent |
| 2 | package browse |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 6 | "encoding/base64" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "log" |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 10 | "net/http" |
| Josh Bleecher Snyder | bf381a7 | 2025-05-29 23:45:02 +0000 | [diff] [blame] | 11 | "net/url" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 12 | "os" |
| 13 | "path/filepath" |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 14 | "strings" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 15 | "sync" |
| 16 | "time" |
| 17 | |
| Philip Zeyliger | 18e3368 | 2025-05-13 16:34:21 -0700 | [diff] [blame] | 18 | "github.com/chromedp/cdproto/runtime" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 19 | "github.com/chromedp/chromedp" |
| 20 | "github.com/google/uuid" |
| 21 | "sketch.dev/llm" |
| 22 | ) |
| 23 | |
| 24 | // ScreenshotDir is the directory where screenshots are stored |
| 25 | const ScreenshotDir = "/tmp/sketch-screenshots" |
| 26 | |
| 27 | // BrowseTools contains all browser tools and manages a shared browser instance |
| 28 | type BrowseTools struct { |
| 29 | ctx context.Context |
| 30 | cancel context.CancelFunc |
| 31 | browserCtx context.Context |
| 32 | browserCtxCancel context.CancelFunc |
| 33 | mux sync.Mutex |
| 34 | initOnce sync.Once |
| 35 | initialized bool |
| 36 | initErr error |
| 37 | // Map to track screenshots by ID and their creation time |
| 38 | screenshots map[string]time.Time |
| 39 | screenshotsMutex sync.Mutex |
| Philip Zeyliger | 18e3368 | 2025-05-13 16:34:21 -0700 | [diff] [blame] | 40 | // Console logs storage |
| 41 | consoleLogs []*runtime.EventConsoleAPICalled |
| 42 | consoleLogsMutex sync.Mutex |
| 43 | maxConsoleLogs int |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 44 | } |
| 45 | |
| 46 | // NewBrowseTools creates a new set of browser automation tools |
| 47 | func NewBrowseTools(ctx context.Context) *BrowseTools { |
| 48 | ctx, cancel := context.WithCancel(ctx) |
| 49 | |
| 50 | // Ensure the screenshot directory exists |
| Autoformatter | 4962f15 | 2025-05-06 17:24:20 +0000 | [diff] [blame] | 51 | if err := os.MkdirAll(ScreenshotDir, 0o755); err != nil { |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 52 | log.Printf("Failed to create screenshot directory: %v", err) |
| 53 | } |
| 54 | |
| 55 | b := &BrowseTools{ |
| Philip Zeyliger | 18e3368 | 2025-05-13 16:34:21 -0700 | [diff] [blame] | 56 | ctx: ctx, |
| 57 | cancel: cancel, |
| 58 | screenshots: make(map[string]time.Time), |
| 59 | consoleLogs: make([]*runtime.EventConsoleAPICalled, 0), |
| 60 | maxConsoleLogs: 100, |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 61 | } |
| 62 | |
| 63 | return b |
| 64 | } |
| 65 | |
| 66 | // Initialize starts the browser if it's not already running |
| 67 | func (b *BrowseTools) Initialize() error { |
| 68 | b.mux.Lock() |
| 69 | defer b.mux.Unlock() |
| 70 | |
| 71 | b.initOnce.Do(func() { |
| 72 | // ChromeDP.ExecPath has a list of common places to find Chrome... |
| 73 | opts := chromedp.DefaultExecAllocatorOptions[:] |
| Philip Zeyliger | c013134 | 2025-06-13 21:07:08 -0700 | [diff] [blame] | 74 | // This is the default when running as root, but we generally need it |
| 75 | // when running in a container, even when we aren't root (which is largely |
| 76 | // the case for tests). |
| 77 | opts = append(opts, chromedp.NoSandbox) |
| Philip Zeyliger | a35de5f | 2025-06-14 12:00:48 -0700 | [diff] [blame] | 78 | // Setting 'DBUS_SESSION_BUS_ADDRESS=""' or this flag allows tests to pass |
| 79 | // in GitHub runner contexts. It's a mystery why the failure isn't clear when this fails. |
| 80 | opts = append(opts, chromedp.Flag("--disable-dbus", true)) |
| 81 | // This can be pretty slow in tests |
| 82 | opts = append(opts, chromedp.WSURLReadTimeout(30*time.Second)) |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 83 | allocCtx, _ := chromedp.NewExecAllocator(b.ctx, opts...) |
| 84 | browserCtx, browserCancel := chromedp.NewContext( |
| 85 | allocCtx, |
| Philip Zeyliger | a35de5f | 2025-06-14 12:00:48 -0700 | [diff] [blame] | 86 | chromedp.WithLogf(log.Printf), chromedp.WithErrorf(log.Printf), chromedp.WithBrowserOption(chromedp.WithDialTimeout(30*time.Second)), |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 87 | ) |
| 88 | |
| 89 | b.browserCtx = browserCtx |
| 90 | b.browserCtxCancel = browserCancel |
| 91 | |
| Philip Zeyliger | 18e3368 | 2025-05-13 16:34:21 -0700 | [diff] [blame] | 92 | // Set up console log listener |
| 93 | chromedp.ListenTarget(browserCtx, func(ev any) { |
| 94 | switch e := ev.(type) { |
| 95 | case *runtime.EventConsoleAPICalled: |
| 96 | b.captureConsoleLog(e) |
| 97 | } |
| 98 | }) |
| 99 | |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 100 | // Ensure the browser starts |
| 101 | if err := chromedp.Run(browserCtx); err != nil { |
| 102 | b.initErr = fmt.Errorf("failed to start browser (please apt get chromium or equivalent): %w", err) |
| 103 | return |
| 104 | } |
| Josh Bleecher Snyder | 7fbc8e4 | 2025-05-29 19:42:25 +0000 | [diff] [blame] | 105 | |
| 106 | // Set default viewport size to 1280x720 (16:9 widescreen) |
| 107 | if err := chromedp.Run(browserCtx, chromedp.EmulateViewport(1280, 720)); err != nil { |
| 108 | b.initErr = fmt.Errorf("failed to set default viewport: %w", err) |
| 109 | return |
| 110 | } |
| 111 | |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 112 | b.initialized = true |
| 113 | }) |
| 114 | |
| 115 | return b.initErr |
| 116 | } |
| 117 | |
| 118 | // Close shuts down the browser |
| 119 | func (b *BrowseTools) Close() { |
| 120 | b.mux.Lock() |
| 121 | defer b.mux.Unlock() |
| 122 | |
| 123 | if b.browserCtxCancel != nil { |
| 124 | b.browserCtxCancel() |
| 125 | b.browserCtxCancel = nil |
| 126 | } |
| 127 | |
| 128 | if b.cancel != nil { |
| 129 | b.cancel() |
| 130 | } |
| 131 | |
| 132 | b.initialized = false |
| 133 | log.Println("Browser closed") |
| 134 | } |
| 135 | |
| 136 | // GetBrowserContext returns the context for browser operations |
| 137 | func (b *BrowseTools) GetBrowserContext() (context.Context, error) { |
| 138 | if err := b.Initialize(); err != nil { |
| 139 | return nil, err |
| 140 | } |
| 141 | return b.browserCtx, nil |
| 142 | } |
| 143 | |
| 144 | // All tools return this as a response when successful |
| 145 | type baseResponse struct { |
| 146 | Status string `json:"status,omitempty"` |
| 147 | } |
| 148 | |
| 149 | func successResponse() string { |
| 150 | return `{"status":"success"}` |
| 151 | } |
| 152 | |
| 153 | func errorResponse(err error) string { |
| 154 | return fmt.Sprintf(`{"status":"error","error":"%s"}`, err.Error()) |
| 155 | } |
| 156 | |
| 157 | // NavigateTool definition |
| 158 | type navigateInput struct { |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 159 | URL string `json:"url"` |
| 160 | Timeout string `json:"timeout,omitempty"` |
| Josh Bleecher Snyder | bf381a7 | 2025-05-29 23:45:02 +0000 | [diff] [blame] | 161 | } |
| 162 | |
| 163 | // isPort80 reports whether urlStr definitely uses port 80. |
| 164 | func isPort80(urlStr string) bool { |
| 165 | parsedURL, err := url.Parse(urlStr) |
| 166 | if err != nil { |
| 167 | return false |
| 168 | } |
| 169 | port := parsedURL.Port() |
| 170 | return port == "80" || (port == "" && parsedURL.Scheme == "http") |
| 171 | } |
| 172 | |
| 173 | // NewNavigateTool creates a tool for navigating to URLs |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 174 | func (b *BrowseTools) NewNavigateTool() *llm.Tool { |
| 175 | return &llm.Tool{ |
| 176 | Name: "browser_navigate", |
| 177 | Description: "Navigate the browser to a specific URL and wait for page to load", |
| 178 | InputSchema: json.RawMessage(`{ |
| 179 | "type": "object", |
| 180 | "properties": { |
| 181 | "url": { |
| 182 | "type": "string", |
| 183 | "description": "The URL to navigate to" |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 184 | }, |
| 185 | "timeout": { |
| 186 | "type": "string", |
| 187 | "description": "Timeout as a Go duration string (default: 5s)" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 188 | } |
| 189 | }, |
| 190 | "required": ["url"] |
| 191 | }`), |
| 192 | Run: b.navigateRun, |
| 193 | } |
| 194 | } |
| 195 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 196 | func (b *BrowseTools) navigateRun(ctx context.Context, m json.RawMessage) ([]llm.Content, error) { |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 197 | var input navigateInput |
| 198 | if err := json.Unmarshal(m, &input); err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 199 | return llm.TextContent(errorResponse(fmt.Errorf("invalid input: %w", err))), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 200 | } |
| 201 | |
| Josh Bleecher Snyder | bf381a7 | 2025-05-29 23:45:02 +0000 | [diff] [blame] | 202 | if isPort80(input.URL) { |
| 203 | return llm.TextContent(errorResponse(fmt.Errorf("port 80 is not the port you're looking for--it is the main sketch server"))), nil |
| 204 | } |
| 205 | |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 206 | browserCtx, err := b.GetBrowserContext() |
| 207 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 208 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 209 | } |
| 210 | |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 211 | // Create a timeout context for this operation |
| 212 | timeoutCtx, cancel := context.WithTimeout(browserCtx, parseTimeout(input.Timeout)) |
| 213 | defer cancel() |
| 214 | |
| 215 | err = chromedp.Run(timeoutCtx, |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 216 | chromedp.Navigate(input.URL), |
| 217 | chromedp.WaitReady("body"), |
| 218 | ) |
| 219 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 220 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 221 | } |
| 222 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 223 | return llm.TextContent(successResponse()), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 224 | } |
| 225 | |
| 226 | // ClickTool definition |
| 227 | type clickInput struct { |
| 228 | Selector string `json:"selector"` |
| 229 | WaitVisible bool `json:"wait_visible,omitempty"` |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 230 | Timeout string `json:"timeout,omitempty"` |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 231 | } |
| 232 | |
| 233 | // NewClickTool creates a tool for clicking elements |
| 234 | func (b *BrowseTools) NewClickTool() *llm.Tool { |
| 235 | return &llm.Tool{ |
| 236 | Name: "browser_click", |
| 237 | Description: "Click the first element matching a CSS selector", |
| 238 | InputSchema: json.RawMessage(`{ |
| 239 | "type": "object", |
| 240 | "properties": { |
| 241 | "selector": { |
| 242 | "type": "string", |
| 243 | "description": "CSS selector for the element to click" |
| 244 | }, |
| 245 | "wait_visible": { |
| 246 | "type": "boolean", |
| 247 | "description": "Wait for the element to be visible before clicking" |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 248 | }, |
| 249 | "timeout": { |
| 250 | "type": "string", |
| 251 | "description": "Timeout as a Go duration string (default: 5s)" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 252 | } |
| 253 | }, |
| 254 | "required": ["selector"] |
| 255 | }`), |
| 256 | Run: b.clickRun, |
| 257 | } |
| 258 | } |
| 259 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 260 | func (b *BrowseTools) clickRun(ctx context.Context, m json.RawMessage) ([]llm.Content, error) { |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 261 | var input clickInput |
| 262 | if err := json.Unmarshal(m, &input); err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 263 | return llm.TextContent(errorResponse(fmt.Errorf("invalid input: %w", err))), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 264 | } |
| 265 | |
| 266 | browserCtx, err := b.GetBrowserContext() |
| 267 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 268 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 269 | } |
| 270 | |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 271 | // Create a timeout context for this operation |
| 272 | timeoutCtx, cancel := context.WithTimeout(browserCtx, parseTimeout(input.Timeout)) |
| 273 | defer cancel() |
| 274 | |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 275 | actions := []chromedp.Action{ |
| 276 | chromedp.WaitReady(input.Selector), |
| 277 | } |
| 278 | |
| 279 | if input.WaitVisible { |
| 280 | actions = append(actions, chromedp.WaitVisible(input.Selector)) |
| 281 | } |
| 282 | |
| 283 | actions = append(actions, chromedp.Click(input.Selector)) |
| 284 | |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 285 | err = chromedp.Run(timeoutCtx, actions...) |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 286 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 287 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 288 | } |
| 289 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 290 | return llm.TextContent(successResponse()), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 291 | } |
| 292 | |
| 293 | // TypeTool definition |
| 294 | type typeInput struct { |
| 295 | Selector string `json:"selector"` |
| 296 | Text string `json:"text"` |
| 297 | Clear bool `json:"clear,omitempty"` |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 298 | Timeout string `json:"timeout,omitempty"` |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 299 | } |
| 300 | |
| 301 | // NewTypeTool creates a tool for typing into input elements |
| 302 | func (b *BrowseTools) NewTypeTool() *llm.Tool { |
| 303 | return &llm.Tool{ |
| 304 | Name: "browser_type", |
| 305 | Description: "Type text into an input or textarea element", |
| 306 | InputSchema: json.RawMessage(`{ |
| 307 | "type": "object", |
| 308 | "properties": { |
| 309 | "selector": { |
| 310 | "type": "string", |
| 311 | "description": "CSS selector for the input element" |
| 312 | }, |
| 313 | "text": { |
| 314 | "type": "string", |
| 315 | "description": "Text to type into the element" |
| 316 | }, |
| 317 | "clear": { |
| 318 | "type": "boolean", |
| 319 | "description": "Clear the input field before typing" |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 320 | }, |
| 321 | "timeout": { |
| 322 | "type": "string", |
| 323 | "description": "Timeout as a Go duration string (default: 5s)" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 324 | } |
| 325 | }, |
| 326 | "required": ["selector", "text"] |
| 327 | }`), |
| 328 | Run: b.typeRun, |
| 329 | } |
| 330 | } |
| 331 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 332 | func (b *BrowseTools) typeRun(ctx context.Context, m json.RawMessage) ([]llm.Content, error) { |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 333 | var input typeInput |
| 334 | if err := json.Unmarshal(m, &input); err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 335 | return llm.TextContent(errorResponse(fmt.Errorf("invalid input: %w", err))), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 336 | } |
| 337 | |
| 338 | browserCtx, err := b.GetBrowserContext() |
| 339 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 340 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 341 | } |
| 342 | |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 343 | // Create a timeout context for this operation |
| 344 | timeoutCtx, cancel := context.WithTimeout(browserCtx, parseTimeout(input.Timeout)) |
| 345 | defer cancel() |
| 346 | |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 347 | actions := []chromedp.Action{ |
| 348 | chromedp.WaitReady(input.Selector), |
| 349 | chromedp.WaitVisible(input.Selector), |
| 350 | } |
| 351 | |
| 352 | if input.Clear { |
| 353 | actions = append(actions, chromedp.Clear(input.Selector)) |
| 354 | } |
| 355 | |
| 356 | actions = append(actions, chromedp.SendKeys(input.Selector, input.Text)) |
| 357 | |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 358 | err = chromedp.Run(timeoutCtx, actions...) |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 359 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 360 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 361 | } |
| 362 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 363 | return llm.TextContent(successResponse()), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 364 | } |
| 365 | |
| 366 | // WaitForTool definition |
| 367 | type waitForInput struct { |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 368 | Selector string `json:"selector"` |
| 369 | Timeout string `json:"timeout,omitempty"` |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 370 | } |
| 371 | |
| 372 | // NewWaitForTool creates a tool for waiting for elements |
| 373 | func (b *BrowseTools) NewWaitForTool() *llm.Tool { |
| 374 | return &llm.Tool{ |
| 375 | Name: "browser_wait_for", |
| 376 | Description: "Wait for an element to be present in the DOM", |
| 377 | InputSchema: json.RawMessage(`{ |
| 378 | "type": "object", |
| 379 | "properties": { |
| 380 | "selector": { |
| 381 | "type": "string", |
| 382 | "description": "CSS selector for the element to wait for" |
| 383 | }, |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 384 | "timeout": { |
| 385 | "type": "string", |
| 386 | "description": "Timeout as a Go duration string (default: 5s)" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 387 | } |
| 388 | }, |
| 389 | "required": ["selector"] |
| 390 | }`), |
| 391 | Run: b.waitForRun, |
| 392 | } |
| 393 | } |
| 394 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 395 | func (b *BrowseTools) waitForRun(ctx context.Context, m json.RawMessage) ([]llm.Content, error) { |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 396 | var input waitForInput |
| 397 | if err := json.Unmarshal(m, &input); err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 398 | return llm.TextContent(errorResponse(fmt.Errorf("invalid input: %w", err))), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 399 | } |
| 400 | |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 401 | browserCtx, err := b.GetBrowserContext() |
| 402 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 403 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 404 | } |
| 405 | |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 406 | timeoutCtx, cancel := context.WithTimeout(browserCtx, parseTimeout(input.Timeout)) |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 407 | defer cancel() |
| 408 | |
| 409 | err = chromedp.Run(timeoutCtx, chromedp.WaitReady(input.Selector)) |
| 410 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 411 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 412 | } |
| 413 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 414 | return llm.TextContent(successResponse()), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 415 | } |
| 416 | |
| 417 | // GetTextTool definition |
| 418 | type getTextInput struct { |
| 419 | Selector string `json:"selector"` |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 420 | Timeout string `json:"timeout,omitempty"` |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 421 | } |
| 422 | |
| 423 | type getTextOutput struct { |
| 424 | Text string `json:"text"` |
| 425 | } |
| 426 | |
| 427 | // NewGetTextTool creates a tool for getting text from elements |
| 428 | func (b *BrowseTools) NewGetTextTool() *llm.Tool { |
| 429 | return &llm.Tool{ |
| 430 | Name: "browser_get_text", |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 431 | Description: "Get the innerText of an element. Can be used to read the web page.", |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 432 | InputSchema: json.RawMessage(`{ |
| 433 | "type": "object", |
| 434 | "properties": { |
| 435 | "selector": { |
| 436 | "type": "string", |
| 437 | "description": "CSS selector for the element to get text from" |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 438 | }, |
| 439 | "timeout": { |
| 440 | "type": "string", |
| 441 | "description": "Timeout as a Go duration string (default: 5s)" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 442 | } |
| 443 | }, |
| 444 | "required": ["selector"] |
| 445 | }`), |
| 446 | Run: b.getTextRun, |
| 447 | } |
| 448 | } |
| 449 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 450 | func (b *BrowseTools) getTextRun(ctx context.Context, m json.RawMessage) ([]llm.Content, error) { |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 451 | var input getTextInput |
| 452 | if err := json.Unmarshal(m, &input); err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 453 | return llm.TextContent(errorResponse(fmt.Errorf("invalid input: %w", err))), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 454 | } |
| 455 | |
| 456 | browserCtx, err := b.GetBrowserContext() |
| 457 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 458 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 459 | } |
| 460 | |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 461 | // Create a timeout context for this operation |
| 462 | timeoutCtx, cancel := context.WithTimeout(browserCtx, parseTimeout(input.Timeout)) |
| 463 | defer cancel() |
| 464 | |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 465 | var text string |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 466 | err = chromedp.Run(timeoutCtx, |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 467 | chromedp.WaitReady(input.Selector), |
| 468 | chromedp.Text(input.Selector, &text), |
| 469 | ) |
| 470 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 471 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 472 | } |
| 473 | |
| 474 | output := getTextOutput{Text: text} |
| 475 | result, err := json.Marshal(output) |
| 476 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 477 | return llm.TextContent(errorResponse(fmt.Errorf("failed to marshal response: %w", err))), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 478 | } |
| 479 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 480 | return llm.TextContent(string(result)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 481 | } |
| 482 | |
| 483 | // EvalTool definition |
| 484 | type evalInput struct { |
| 485 | Expression string `json:"expression"` |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 486 | Timeout string `json:"timeout,omitempty"` |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 487 | } |
| 488 | |
| 489 | type evalOutput struct { |
| 490 | Result any `json:"result"` |
| 491 | } |
| 492 | |
| 493 | // NewEvalTool creates a tool for evaluating JavaScript |
| 494 | func (b *BrowseTools) NewEvalTool() *llm.Tool { |
| 495 | return &llm.Tool{ |
| 496 | Name: "browser_eval", |
| 497 | Description: "Evaluate JavaScript in the browser context", |
| 498 | InputSchema: json.RawMessage(`{ |
| 499 | "type": "object", |
| 500 | "properties": { |
| 501 | "expression": { |
| 502 | "type": "string", |
| 503 | "description": "JavaScript expression to evaluate" |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 504 | }, |
| 505 | "timeout": { |
| 506 | "type": "string", |
| 507 | "description": "Timeout as a Go duration string (default: 5s)" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 508 | } |
| 509 | }, |
| 510 | "required": ["expression"] |
| 511 | }`), |
| 512 | Run: b.evalRun, |
| 513 | } |
| 514 | } |
| 515 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 516 | func (b *BrowseTools) evalRun(ctx context.Context, m json.RawMessage) ([]llm.Content, error) { |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 517 | var input evalInput |
| 518 | if err := json.Unmarshal(m, &input); err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 519 | return llm.TextContent(errorResponse(fmt.Errorf("invalid input: %w", err))), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 520 | } |
| 521 | |
| 522 | browserCtx, err := b.GetBrowserContext() |
| 523 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 524 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 525 | } |
| 526 | |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 527 | // Create a timeout context for this operation |
| 528 | timeoutCtx, cancel := context.WithTimeout(browserCtx, parseTimeout(input.Timeout)) |
| 529 | defer cancel() |
| 530 | |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 531 | var result any |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 532 | err = chromedp.Run(timeoutCtx, chromedp.Evaluate(input.Expression, &result)) |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 533 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 534 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 535 | } |
| 536 | |
| 537 | output := evalOutput{Result: result} |
| 538 | response, err := json.Marshal(output) |
| 539 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 540 | return llm.TextContent(errorResponse(fmt.Errorf("failed to marshal response: %w", err))), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 541 | } |
| 542 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 543 | return llm.TextContent(string(response)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 544 | } |
| 545 | |
| 546 | // ScreenshotTool definition |
| 547 | type screenshotInput struct { |
| 548 | Selector string `json:"selector,omitempty"` |
| 549 | Format string `json:"format,omitempty"` |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 550 | Timeout string `json:"timeout,omitempty"` |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 551 | } |
| 552 | |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 553 | // NewScreenshotTool creates a tool for taking screenshots |
| 554 | func (b *BrowseTools) NewScreenshotTool() *llm.Tool { |
| 555 | return &llm.Tool{ |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 556 | Name: "browser_take_screenshot", |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 557 | Description: "Take a screenshot of the page or a specific element", |
| 558 | InputSchema: json.RawMessage(`{ |
| 559 | "type": "object", |
| 560 | "properties": { |
| 561 | "selector": { |
| 562 | "type": "string", |
| Josh Bleecher Snyder | 74d690e | 2025-05-14 18:16:03 -0700 | [diff] [blame] | 563 | "description": "CSS selector for the element to screenshot (optional)" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 564 | }, |
| 565 | "format": { |
| 566 | "type": "string", |
| 567 | "description": "Output format ('base64' or 'png'), defaults to 'base64'", |
| 568 | "enum": ["base64", "png"] |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 569 | }, |
| 570 | "timeout": { |
| 571 | "type": "string", |
| 572 | "description": "Timeout as a Go duration string (default: 5s)" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 573 | } |
| 574 | } |
| 575 | }`), |
| 576 | Run: b.screenshotRun, |
| 577 | } |
| 578 | } |
| 579 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 580 | func (b *BrowseTools) screenshotRun(ctx context.Context, m json.RawMessage) ([]llm.Content, error) { |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 581 | var input screenshotInput |
| 582 | if err := json.Unmarshal(m, &input); err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 583 | return llm.TextContent(errorResponse(fmt.Errorf("invalid input: %w", err))), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 584 | } |
| 585 | |
| 586 | browserCtx, err := b.GetBrowserContext() |
| 587 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 588 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 589 | } |
| 590 | |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 591 | // Create a timeout context for this operation |
| 592 | timeoutCtx, cancel := context.WithTimeout(browserCtx, parseTimeout(input.Timeout)) |
| 593 | defer cancel() |
| 594 | |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 595 | var buf []byte |
| 596 | var actions []chromedp.Action |
| 597 | |
| 598 | if input.Selector != "" { |
| 599 | // Take screenshot of specific element |
| 600 | actions = append(actions, |
| 601 | chromedp.WaitReady(input.Selector), |
| 602 | chromedp.Screenshot(input.Selector, &buf, chromedp.NodeVisible), |
| 603 | ) |
| 604 | } else { |
| 605 | // Take full page screenshot |
| 606 | actions = append(actions, chromedp.CaptureScreenshot(&buf)) |
| 607 | } |
| 608 | |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 609 | err = chromedp.Run(timeoutCtx, actions...) |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 610 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 611 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 612 | } |
| 613 | |
| Philip Zeyliger | 542bda3 | 2025-06-11 18:31:03 -0700 | [diff] [blame] | 614 | // Save the screenshot and get its ID for potential future reference |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 615 | id := b.SaveScreenshot(buf) |
| 616 | if id == "" { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 617 | return llm.TextContent(errorResponse(fmt.Errorf("failed to save screenshot"))), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 618 | } |
| 619 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 620 | // Get the full path to the screenshot |
| 621 | screenshotPath := GetScreenshotPath(id) |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 622 | |
| Philip Zeyliger | 542bda3 | 2025-06-11 18:31:03 -0700 | [diff] [blame] | 623 | // Encode the image as base64 |
| 624 | base64Data := base64.StdEncoding.EncodeToString(buf) |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 625 | |
| Philip Zeyliger | 542bda3 | 2025-06-11 18:31:03 -0700 | [diff] [blame] | 626 | // Return the screenshot directly to the LLM |
| 627 | return []llm.Content{ |
| 628 | { |
| 629 | Type: llm.ContentTypeText, |
| 630 | Text: fmt.Sprintf("Screenshot taken (saved as %s)", screenshotPath), |
| 631 | }, |
| 632 | { |
| 633 | Type: llm.ContentTypeText, // Will be mapped to image in content array |
| 634 | MediaType: "image/png", |
| 635 | Data: base64Data, |
| 636 | }, |
| 637 | }, nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 638 | } |
| 639 | |
| 640 | // ScrollIntoViewTool definition |
| 641 | type scrollIntoViewInput struct { |
| 642 | Selector string `json:"selector"` |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 643 | Timeout string `json:"timeout,omitempty"` |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 644 | } |
| 645 | |
| 646 | // NewScrollIntoViewTool creates a tool for scrolling elements into view |
| 647 | func (b *BrowseTools) NewScrollIntoViewTool() *llm.Tool { |
| 648 | return &llm.Tool{ |
| 649 | Name: "browser_scroll_into_view", |
| 650 | Description: "Scroll an element into view if it's not visible", |
| 651 | InputSchema: json.RawMessage(`{ |
| 652 | "type": "object", |
| 653 | "properties": { |
| 654 | "selector": { |
| 655 | "type": "string", |
| 656 | "description": "CSS selector for the element to scroll into view" |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 657 | }, |
| 658 | "timeout": { |
| 659 | "type": "string", |
| 660 | "description": "Timeout as a Go duration string (default: 5s)" |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 661 | } |
| 662 | }, |
| 663 | "required": ["selector"] |
| 664 | }`), |
| 665 | Run: b.scrollIntoViewRun, |
| 666 | } |
| 667 | } |
| 668 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 669 | func (b *BrowseTools) scrollIntoViewRun(ctx context.Context, m json.RawMessage) ([]llm.Content, error) { |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 670 | var input scrollIntoViewInput |
| 671 | if err := json.Unmarshal(m, &input); err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 672 | return llm.TextContent(errorResponse(fmt.Errorf("invalid input: %w", err))), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 673 | } |
| 674 | |
| 675 | browserCtx, err := b.GetBrowserContext() |
| 676 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 677 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 678 | } |
| 679 | |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 680 | // Create a timeout context for this operation |
| 681 | timeoutCtx, cancel := context.WithTimeout(browserCtx, parseTimeout(input.Timeout)) |
| 682 | defer cancel() |
| 683 | |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 684 | script := fmt.Sprintf(` |
| 685 | const el = document.querySelector('%s'); |
| 686 | if (el) { |
| 687 | el.scrollIntoView({behavior: 'smooth', block: 'center'}); |
| 688 | return true; |
| 689 | } |
| 690 | return false; |
| 691 | `, input.Selector) |
| 692 | |
| 693 | var result bool |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 694 | err = chromedp.Run(timeoutCtx, |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 695 | chromedp.WaitReady(input.Selector), |
| 696 | chromedp.Evaluate(script, &result), |
| 697 | ) |
| 698 | if err != nil { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 699 | return llm.TextContent(errorResponse(err)), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 700 | } |
| 701 | |
| 702 | if !result { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 703 | return llm.TextContent(errorResponse(fmt.Errorf("element not found: %s", input.Selector))), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 704 | } |
| 705 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 706 | return llm.TextContent(successResponse()), nil |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 707 | } |
| 708 | |
| Philip Zeyliger | 0522484 | 2025-05-10 18:26:08 -0700 | [diff] [blame] | 709 | // ResizeTool definition |
| 710 | type resizeInput struct { |
| 711 | Width int `json:"width"` |
| 712 | Height int `json:"height"` |
| 713 | Timeout string `json:"timeout,omitempty"` |
| 714 | } |
| 715 | |
| 716 | // NewResizeTool creates a tool for resizing the browser window |
| 717 | func (b *BrowseTools) NewResizeTool() *llm.Tool { |
| 718 | return &llm.Tool{ |
| 719 | Name: "browser_resize", |
| 720 | Description: "Resize the browser window to a specific width and height", |
| 721 | InputSchema: json.RawMessage(`{ |
| 722 | "type": "object", |
| 723 | "properties": { |
| 724 | "width": { |
| 725 | "type": "integer", |
| 726 | "description": "Window width in pixels" |
| 727 | }, |
| 728 | "height": { |
| 729 | "type": "integer", |
| 730 | "description": "Window height in pixels" |
| 731 | }, |
| 732 | "timeout": { |
| 733 | "type": "string", |
| 734 | "description": "Timeout as a Go duration string (default: 5s)" |
| 735 | } |
| 736 | }, |
| 737 | "required": ["width", "height"] |
| 738 | }`), |
| 739 | Run: b.resizeRun, |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | func (b *BrowseTools) resizeRun(ctx context.Context, m json.RawMessage) ([]llm.Content, error) { |
| 744 | var input resizeInput |
| 745 | if err := json.Unmarshal(m, &input); err != nil { |
| 746 | return llm.TextContent(errorResponse(fmt.Errorf("invalid input: %w", err))), nil |
| 747 | } |
| 748 | |
| 749 | browserCtx, err := b.GetBrowserContext() |
| 750 | if err != nil { |
| 751 | return llm.TextContent(errorResponse(err)), nil |
| 752 | } |
| 753 | |
| 754 | // Create a timeout context for this operation |
| 755 | timeoutCtx, cancel := context.WithTimeout(browserCtx, parseTimeout(input.Timeout)) |
| 756 | defer cancel() |
| 757 | |
| 758 | // Validate dimensions |
| 759 | if input.Width <= 0 || input.Height <= 0 { |
| 760 | return llm.TextContent(errorResponse(fmt.Errorf("invalid dimensions: width and height must be positive"))), nil |
| 761 | } |
| 762 | |
| 763 | // Resize the browser window |
| 764 | err = chromedp.Run(timeoutCtx, |
| 765 | chromedp.EmulateViewport(int64(input.Width), int64(input.Height)), |
| 766 | ) |
| 767 | if err != nil { |
| 768 | return llm.TextContent(errorResponse(err)), nil |
| 769 | } |
| 770 | |
| 771 | return llm.TextContent(successResponse()), nil |
| 772 | } |
| 773 | |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 774 | // GetTools returns browser tools, optionally filtering out screenshot-related tools |
| 775 | func (b *BrowseTools) GetTools(includeScreenshotTools bool) []*llm.Tool { |
| 776 | tools := []*llm.Tool{ |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 777 | b.NewNavigateTool(), |
| 778 | b.NewClickTool(), |
| 779 | b.NewTypeTool(), |
| 780 | b.NewWaitForTool(), |
| 781 | b.NewGetTextTool(), |
| 782 | b.NewEvalTool(), |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 783 | b.NewScrollIntoViewTool(), |
| Philip Zeyliger | 0522484 | 2025-05-10 18:26:08 -0700 | [diff] [blame] | 784 | b.NewResizeTool(), |
| Philip Zeyliger | 18e3368 | 2025-05-13 16:34:21 -0700 | [diff] [blame] | 785 | b.NewRecentConsoleLogsTool(), |
| 786 | b.NewClearConsoleLogsTool(), |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 787 | } |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 788 | |
| 789 | // Add screenshot-related tools if supported |
| 790 | if includeScreenshotTools { |
| 791 | tools = append(tools, b.NewScreenshotTool()) |
| 792 | tools = append(tools, b.NewReadImageTool()) |
| 793 | } |
| 794 | |
| 795 | return tools |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 796 | } |
| 797 | |
| 798 | // SaveScreenshot saves a screenshot to disk and returns its ID |
| 799 | func (b *BrowseTools) SaveScreenshot(data []byte) string { |
| 800 | // Generate a unique ID |
| 801 | id := uuid.New().String() |
| 802 | |
| 803 | // Save the file |
| 804 | filePath := filepath.Join(ScreenshotDir, id+".png") |
| Autoformatter | 4962f15 | 2025-05-06 17:24:20 +0000 | [diff] [blame] | 805 | if err := os.WriteFile(filePath, data, 0o644); err != nil { |
| Philip Zeyliger | 33d282f | 2025-05-03 04:01:54 +0000 | [diff] [blame] | 806 | log.Printf("Failed to save screenshot: %v", err) |
| 807 | return "" |
| 808 | } |
| 809 | |
| 810 | // Track this screenshot |
| 811 | b.screenshotsMutex.Lock() |
| 812 | b.screenshots[id] = time.Now() |
| 813 | b.screenshotsMutex.Unlock() |
| 814 | |
| 815 | return id |
| 816 | } |
| 817 | |
| 818 | // GetScreenshotPath returns the full path to a screenshot by ID |
| 819 | func GetScreenshotPath(id string) string { |
| 820 | return filepath.Join(ScreenshotDir, id+".png") |
| 821 | } |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 822 | |
| 823 | // ReadImageTool definition |
| 824 | type readImageInput struct { |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 825 | Path string `json:"path"` |
| 826 | Timeout string `json:"timeout,omitempty"` |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 827 | } |
| 828 | |
| 829 | // NewReadImageTool creates a tool for reading images and returning them as base64 encoded data |
| 830 | func (b *BrowseTools) NewReadImageTool() *llm.Tool { |
| 831 | return &llm.Tool{ |
| Philip Zeyliger | 542bda3 | 2025-06-11 18:31:03 -0700 | [diff] [blame] | 832 | Name: "read_image", |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 833 | Description: "Read an image file (such as a screenshot) and encode it for sending to the LLM", |
| 834 | InputSchema: json.RawMessage(`{ |
| 835 | "type": "object", |
| 836 | "properties": { |
| 837 | "path": { |
| 838 | "type": "string", |
| 839 | "description": "Path to the image file to read" |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 840 | }, |
| 841 | "timeout": { |
| 842 | "type": "string", |
| 843 | "description": "Timeout as a Go duration string (default: 5s)" |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 844 | } |
| 845 | }, |
| 846 | "required": ["path"] |
| 847 | }`), |
| 848 | Run: b.readImageRun, |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | func (b *BrowseTools) readImageRun(ctx context.Context, m json.RawMessage) ([]llm.Content, error) { |
| 853 | var input readImageInput |
| 854 | if err := json.Unmarshal(m, &input); err != nil { |
| 855 | return llm.TextContent(errorResponse(fmt.Errorf("invalid input: %w", err))), nil |
| 856 | } |
| 857 | |
| 858 | // Check if the path exists |
| 859 | if _, err := os.Stat(input.Path); os.IsNotExist(err) { |
| 860 | return llm.TextContent(errorResponse(fmt.Errorf("image file not found: %s", input.Path))), nil |
| 861 | } |
| 862 | |
| 863 | // Read the file |
| 864 | imageData, err := os.ReadFile(input.Path) |
| 865 | if err != nil { |
| 866 | return llm.TextContent(errorResponse(fmt.Errorf("failed to read image file: %w", err))), nil |
| 867 | } |
| 868 | |
| 869 | // Detect the image type |
| 870 | imageType := http.DetectContentType(imageData) |
| 871 | if !strings.HasPrefix(imageType, "image/") { |
| 872 | return llm.TextContent(errorResponse(fmt.Errorf("file is not an image: %s", imageType))), nil |
| 873 | } |
| 874 | |
| 875 | // Encode the image as base64 |
| 876 | base64Data := base64.StdEncoding.EncodeToString(imageData) |
| 877 | |
| 878 | // Create a Content object that includes both text and the image |
| 879 | return []llm.Content{ |
| 880 | { |
| 881 | Type: llm.ContentTypeText, |
| 882 | Text: fmt.Sprintf("Image from %s (type: %s)", input.Path, imageType), |
| 883 | }, |
| 884 | { |
| 885 | Type: llm.ContentTypeText, // Will be mapped to image in content array |
| 886 | MediaType: imageType, |
| 887 | Data: base64Data, |
| 888 | }, |
| 889 | }, nil |
| 890 | } |
| Philip Zeyliger | 80b488d | 2025-05-10 18:21:54 -0700 | [diff] [blame] | 891 | |
| 892 | // parseTimeout parses a timeout string and returns a time.Duration |
| 893 | // It returns a default of 5 seconds if the timeout is empty or invalid |
| 894 | func parseTimeout(timeout string) time.Duration { |
| 895 | if timeout == "" { |
| 896 | return 5 * time.Second // default 5 seconds |
| 897 | } |
| 898 | |
| 899 | dur, err := time.ParseDuration(timeout) |
| 900 | if err != nil { |
| 901 | // If parsing fails, return the default |
| 902 | return 5 * time.Second |
| 903 | } |
| 904 | |
| 905 | return dur |
| 906 | } |
| Philip Zeyliger | 18e3368 | 2025-05-13 16:34:21 -0700 | [diff] [blame] | 907 | |
| 908 | // captureConsoleLog captures a console log event and stores it |
| 909 | func (b *BrowseTools) captureConsoleLog(e *runtime.EventConsoleAPICalled) { |
| 910 | // Add to logs with mutex protection |
| 911 | b.consoleLogsMutex.Lock() |
| 912 | defer b.consoleLogsMutex.Unlock() |
| 913 | |
| 914 | // Add the log and maintain max size |
| 915 | b.consoleLogs = append(b.consoleLogs, e) |
| 916 | if len(b.consoleLogs) > b.maxConsoleLogs { |
| 917 | b.consoleLogs = b.consoleLogs[len(b.consoleLogs)-b.maxConsoleLogs:] |
| 918 | } |
| 919 | } |
| 920 | |
| 921 | // RecentConsoleLogsTool definition |
| 922 | type recentConsoleLogsInput struct { |
| 923 | Limit int `json:"limit,omitempty"` |
| 924 | } |
| 925 | |
| 926 | // NewRecentConsoleLogsTool creates a tool for retrieving recent console logs |
| 927 | func (b *BrowseTools) NewRecentConsoleLogsTool() *llm.Tool { |
| 928 | return &llm.Tool{ |
| 929 | Name: "browser_recent_console_logs", |
| 930 | Description: "Get recent browser console logs", |
| 931 | InputSchema: json.RawMessage(`{ |
| 932 | "type": "object", |
| 933 | "properties": { |
| 934 | "limit": { |
| 935 | "type": "integer", |
| 936 | "description": "Maximum number of log entries to return (default: 100)" |
| 937 | } |
| 938 | } |
| 939 | }`), |
| 940 | Run: b.recentConsoleLogsRun, |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | func (b *BrowseTools) recentConsoleLogsRun(ctx context.Context, m json.RawMessage) ([]llm.Content, error) { |
| 945 | var input recentConsoleLogsInput |
| 946 | if err := json.Unmarshal(m, &input); err != nil { |
| 947 | return llm.TextContent(errorResponse(fmt.Errorf("invalid input: %w", err))), nil |
| 948 | } |
| 949 | |
| 950 | // Ensure browser is initialized |
| 951 | _, err := b.GetBrowserContext() |
| 952 | if err != nil { |
| 953 | return llm.TextContent(errorResponse(err)), nil |
| 954 | } |
| 955 | |
| 956 | // Apply limit (default to 100 if not specified) |
| 957 | limit := 100 |
| 958 | if input.Limit > 0 { |
| 959 | limit = input.Limit |
| 960 | } |
| 961 | |
| 962 | // Get console logs with mutex protection |
| 963 | b.consoleLogsMutex.Lock() |
| 964 | logs := make([]*runtime.EventConsoleAPICalled, 0, len(b.consoleLogs)) |
| 965 | start := 0 |
| 966 | if len(b.consoleLogs) > limit { |
| 967 | start = len(b.consoleLogs) - limit |
| 968 | } |
| 969 | logs = append(logs, b.consoleLogs[start:]...) |
| 970 | b.consoleLogsMutex.Unlock() |
| 971 | |
| 972 | // Format the logs as JSON |
| 973 | logData, err := json.MarshalIndent(logs, "", " ") |
| 974 | if err != nil { |
| 975 | return llm.TextContent(errorResponse(fmt.Errorf("failed to serialize logs: %w", err))), nil |
| 976 | } |
| 977 | |
| 978 | // Format the logs |
| 979 | var sb strings.Builder |
| 980 | sb.WriteString(fmt.Sprintf("Retrieved %d console log entries:\n\n", len(logs))) |
| 981 | |
| 982 | if len(logs) == 0 { |
| 983 | sb.WriteString("No console logs captured.") |
| 984 | } else { |
| 985 | // Add the JSON data for full details |
| 986 | sb.WriteString(string(logData)) |
| 987 | } |
| 988 | |
| 989 | return llm.TextContent(sb.String()), nil |
| 990 | } |
| 991 | |
| 992 | // ClearConsoleLogsTool definition |
| 993 | type clearConsoleLogsInput struct{} |
| 994 | |
| 995 | // NewClearConsoleLogsTool creates a tool for clearing console logs |
| 996 | func (b *BrowseTools) NewClearConsoleLogsTool() *llm.Tool { |
| 997 | return &llm.Tool{ |
| 998 | Name: "browser_clear_console_logs", |
| 999 | Description: "Clear all captured browser console logs", |
| Josh Bleecher Snyder | 74d690e | 2025-05-14 18:16:03 -0700 | [diff] [blame] | 1000 | InputSchema: llm.EmptySchema(), |
| 1001 | Run: b.clearConsoleLogsRun, |
| Philip Zeyliger | 18e3368 | 2025-05-13 16:34:21 -0700 | [diff] [blame] | 1002 | } |
| 1003 | } |
| 1004 | |
| 1005 | func (b *BrowseTools) clearConsoleLogsRun(ctx context.Context, m json.RawMessage) ([]llm.Content, error) { |
| 1006 | var input clearConsoleLogsInput |
| 1007 | if err := json.Unmarshal(m, &input); err != nil { |
| 1008 | return llm.TextContent(errorResponse(fmt.Errorf("invalid input: %w", err))), nil |
| 1009 | } |
| 1010 | |
| 1011 | // Ensure browser is initialized |
| 1012 | _, err := b.GetBrowserContext() |
| 1013 | if err != nil { |
| 1014 | return llm.TextContent(errorResponse(err)), nil |
| 1015 | } |
| 1016 | |
| 1017 | // Clear console logs with mutex protection |
| 1018 | b.consoleLogsMutex.Lock() |
| 1019 | logCount := len(b.consoleLogs) |
| 1020 | b.consoleLogs = make([]*runtime.EventConsoleAPICalled, 0) |
| 1021 | b.consoleLogsMutex.Unlock() |
| 1022 | |
| 1023 | return llm.TextContent(fmt.Sprintf("Cleared %d console log entries.", logCount)), nil |
| 1024 | } |