webtool

package
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 21 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

webtool

webtool provides browser-backed web tools for the ds4 agent loop, matching the design of the upstream ds4 inference engine's browser helper (ds4_web.c).

It enables DeepSeek agent loops to search Google and visit web pages using a local Google Chrome or Chromium installation, and to fetch an image from the web as a visual observation for a vision model (fetch_image, which needs no browser).

How it Works

  1. Auto-Detection: The package automatically searches standard locations on macOS and Linux for a Google Chrome or Chromium executable (or reads the DS4_CHROME environment variable).
  2. Process Management: It starts a visible Google Chrome process in the background configured with remote debugging enabled (--remote-debugging-port) and a dedicated user data directory (~/.ds4/browser).
  3. CDP over Raw WebSockets: It connects to Chrome using the Chrome DevTools Protocol (CDP). To remain zero-dependency, it uses a lightweight, custom RFC 6455 WebSocket client implementation built on top of standard Go sockets.
  4. Markdown Extraction: It navigates to pages, automatically bypasses Google Search consent forms, triggers lazy-loaded content by scrolling, and runs JavaScript-based Markdown extractors to compile clean structured text snapshots of pages.

Usage

You can initialize webtool.NewWebHelper and register its tools (GoogleSearchTool(), VisitPageTool(), and FetchImageTool()) directly into a ds4.ToolRegistry:

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/NimbleMarkets/ds4go"
	"github.com/NimbleMarkets/ds4go/webtool"
)

func main() {
	// Initialize the helper
	helper := webtool.NewWebHelper(webtool.Config{
		Port: 9333,
		ConfirmApproval: func(message string) (bool, error) {
			// Web tools require explicit user confirmation to launch Chrome for the first time
			fmt.Print(message)
			var input string
			_, err := fmt.Scanln(&input)
			if err != nil {
				return false, err
			}
			input = strings.ToLower(strings.TrimSpace(input))
			return input == "y" || input == "yes", nil
		},
		Log: func(msg string) {
			log.Printf("[Browser Log] %s\n", msg)
		},
	})
	// Keep the browser running across tool execution rounds, but clean up on shutdown
	defer helper.Close()

	// Register tools
	reg := ds4.NewToolRegistry()
	reg.MustRegister(helper.GoogleSearchTool())
	reg.MustRegister(helper.VisitPageTool())

	// Configure and run the ds4 ToolLoop...
}

Available Tools

The following tools are exposed to the DeepSeek model:

  • Description: Search Google in a visible browser and return compact Markdown links.
  • Arguments:
    {
      "query": "search query string"
    }
    
visit_page
  • Description: Open a URL in a visible browser and return rendered page Markdown. Only http(s) URLs are opened; loopback, private, and link-local destinations are refused unless AllowPrivateFetch, including the page a redirect lands on.
  • Arguments:
    {
      "url": "https://example.com"
    }
    

Configuration Options

The webtool.Config struct accepts the following configuration fields:

Field Type Description
HomeDir string Directory containing user configuration. Defaults to $HOME, or . if unset. The Chrome user profile is stored at HomeDir + "/.ds4/browser".
Port int Remote debugging port to use for the Chrome session. Defaults to 9333.
ChromePath string Explicit path to the Chrome or Chromium executable. If empty, the helper will search standard paths.
ConfirmApproval func(string) (bool, error) Required. Callback invoked to request permission from the user before starting Chrome for the first time.
Log func(string) Optional logger callback for receiving status messages from the browser manager.
SearchProvider string Search engine to use: "google", "duckduckgo", "bing", "yahoo", "yandex", "baidu", or "brave". Defaults to "google".
VisionAvailable func() bool Whether the engine can encode images (engine.HasVision). When nil or false, fetch_image returns a text observation asking for --vision.
AllowPrivateFetch bool Let fetch_image and visit_page reach loopback, private, and link-local addresses, directly or via redirect. Off by default. Non-http(s) schemes such as file:// are refused either way.
MaxImageBytes int Cap on one fetched image. Defaults to 64 MiB, upstream's image limit.
HTTPClient *http.Client Client used by fetch_image. Defaults to one with a 60 s timeout.

fetch_image

fetch_image downloads a PNG or JPEG over http(s) and returns it as an image observation, the web counterpart of workspacetool's view_image. The tool loop must have an Images encoder set; the bytes travel in the observation so history re-renders without refetching. The body is accepted by file signature, not Content-Type, and capped at MaxImageBytes. Destinations that resolve to private, loopback, or link-local addresses are refused on every hop unless AllowPrivateFetch is set, so a model cannot be steered at services behind the tool's host. The check runs on the address actually dialed, so a name whose DNS answer changes between lookups (rebinding) gains nothing; a custom HTTPClient must therefore use an *http.Transport, or set AllowPrivateFetch. Without a vision encoder the tool answers with a text hint rather than failing, matching upstream view_image.

Documentation

Index

Constants

View Source
const FetchImageParametersSchema = `` /* 155-byte string literal not displayed */

FetchImageParametersSchema is the JSON schema for the fetch_image tool.

View Source
const GoogleSearchParametersSchema = `{
	"type": "object",
	"properties": {
		"query": {
			"type": "string"
		}
	},
	"required": [
		"query"
	]
}`
View Source
const VisitPageParametersSchema = `{
	"type": "object",
	"properties": {
		"url": {
			"type": "string"
		}
	},
	"required": [
		"url"
	]
}`

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// HomeDir is the directory containing user configuration.
	// Defaults to $HOME, or "." if unset.
	HomeDir string
	// Port is the debugging port to run Chrome on. Defaults to 9333.
	Port int
	// ChromePath is the path to the Chrome or Chromium executable.
	// If empty, auto-detection searches standard paths.
	ChromePath string
	// ConfirmApproval is called to prompt the user before starting Chrome for the first time.
	// If nil, starting Chrome will fail with an error.
	ConfirmApproval func(message string) (bool, error)
	// Log receives status messages from the helper.
	Log func(message string)
	// SearchProvider specifies the search engine to use.
	// Supported values: "google" (default), "duckduckgo", "bing".
	SearchProvider string
	// VisionAvailable reports whether the engine can encode images. When nil
	// or false, fetch_image returns a text observation asking for --vision.
	VisionAvailable func() bool
	// AllowPrivateFetch lets fetch_image and visit_page reach loopback,
	// private, and link-local addresses, on the first hop or via redirect.
	// Off by default so a model cannot be steered at services behind the
	// tool's host. Non-http(s) schemes such as file:// are refused either way.
	AllowPrivateFetch bool
	// MaxImageBytes caps one fetched image. Zero means upstream's 64 MiB.
	MaxImageBytes int
	// HTTPClient serves fetch_image; nil uses a client with a 60 s timeout.
	HTTPClient *http.Client
}

Config configures the WebHelper.

type WebHelper

type WebHelper struct {
	// contains filtered or unexported fields
}

WebHelper implements browser-backed web tools using Chrome DevTools Protocol.

func NewWebHelper

func NewWebHelper(cfg Config) *WebHelper

NewWebHelper creates a new WebHelper.

func (*WebHelper) Close

func (w *WebHelper) Close() error

Close terminates the spawned Chrome browser if it was started by this helper.

func (*WebHelper) FetchImageTool added in v0.7.0

func (w *WebHelper) FetchImageTool() ds4.ToolHandler

FetchImageTool returns fetch_image: download a PNG or JPEG over http(s) and hand it to the model as a visual observation, the web counterpart of workspacetool's view_image. The bytes travel in the observation, so the tool loop encodes them once and re-renders history without refetching. The body is accepted by signature, not Content-Type, and capped at Config.MaxImageBytes. Private, loopback, and link-local destinations are refused on every hop unless Config.AllowPrivateFetch is set. Without a vision encoder it returns a text observation rather than an error, so the model can carry on, matching view_image.

func (*WebHelper) GoogleSearch

func (w *WebHelper) GoogleSearch(ctx context.Context, query string) (string, error)

GoogleSearch searches Google (or the default configured SearchProvider) and returns search result Markdown links.

func (*WebHelper) GoogleSearchTool

func (w *WebHelper) GoogleSearchTool() ds4.Tool

GoogleSearchTool returns the Tool schema and handler for Google Search.

func (*WebHelper) Search

func (w *WebHelper) Search(ctx context.Context, query string, provider string) (string, error)

Search executes a web search using the specified provider and returns Markdown links. Supported providers: "google", "duckduckgo", "bing". If provider is empty, the default configured SearchProvider is used (falling back to "google").

func (*WebHelper) VisitPage

func (w *WebHelper) VisitPage(ctx context.Context, targetURL string) (string, error)

VisitPage navigates to a URL, optionally scrolls, and extracts its text layout. The URL passes the same policy as fetch_image first: http(s) only, and no loopback, private, or link-local destination unless Config.AllowPrivateFetch, checked again on the page the browser lands on. The browser would otherwise render file://, chrome://, and internal services for a model steered by page content.

func (*WebHelper) VisitPageTool

func (w *WebHelper) VisitPageTool() ds4.Tool

VisitPageTool returns the Tool schema and handler for visiting web pages.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL