From d47a71f77923a9fce0c2d7d165fb09eb2a4d809e Mon Sep 17 00:00:00 2001 From: sausheong Date: Mon, 28 Sep 2026 01:25:08 +0800 Subject: [PATCH] feat: Stagehand natural-language browser tool Add tools/stagehand, a browser tool built on the Stagehand Go SDK (act/observe/extract/navigate/get_text/screenshot) with persistent named sessions. Runs on local Chrome by default or Browserbase when an API key is configured. Stagehand's internal inference is routed through the harness LLMProvider via NewGenerateFunc, so it shares the agent's provider, usage observers and admission guards. The Stagehand SDK requires Go 1.26, so the module now declares go 1.26.0. --- README.md | 8 +- developer.md | 2 +- go.mod | 10 +- go.sum | 20 +- tools/stagehand/generate.go | 328 +++++++++++++++ tools/stagehand/generate_test.go | 211 ++++++++++ tools/stagehand/stagehand.go | 535 +++++++++++++++++++++++++ tools/stagehand/stagehand_live_test.go | 72 ++++ tools/stagehand/stagehand_test.go | 190 +++++++++ 9 files changed, 1369 insertions(+), 7 deletions(-) create mode 100644 tools/stagehand/generate.go create mode 100644 tools/stagehand/generate_test.go create mode 100644 tools/stagehand/stagehand.go create mode 100644 tools/stagehand/stagehand_live_test.go create mode 100644 tools/stagehand/stagehand_test.go diff --git a/README.md b/README.md index 117cb3d..b349fa3 100644 --- a/README.md +++ b/README.md @@ -132,9 +132,9 @@ a lot. The package is optimized for the use cases above, not these. ## Requirements -- **Go 1.25.1 or newer.** The module declares `go 1.25.1` and uses - `iter.Seq` from `iter` (Go 1.23+) plus a few stdlib calls that - hardened in 1.25. Older toolchains will fail at `go build`. +- **Go 1.26 or newer.** The module declares `go 1.26.0`, required by + the Stagehand SDK that `tools/stagehand` depends on. With the default + `GOTOOLCHAIN=auto`, an older local Go downloads 1.26 automatically. - **An LLM API key**, depending on which provider(s) you wire in: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, Google ADC for Gemini, or a LiteLLM/OpenRouter key for those aggregators. For local models @@ -183,6 +183,8 @@ github.com/sausheong/harness/ ├── bash/ # bash (with ExecPolicy: deny | allowlist | full) ├── web/ # web_fetch, web_search, ssrf guard ├── browser/ # chromedp wrapper with per-session reuse + ├── stagehand/ # natural-language browser (Stagehand: act/observe/extract), + │ # local Chrome or Browserbase; inference via your LLMProvider ├── mcp/ # Connect to external MCP servers; adapt their tools └── todo/ # todo_write ``` diff --git a/developer.md b/developer.md index b8cfc12..c694acb 100644 --- a/developer.md +++ b/developer.md @@ -1,7 +1,7 @@ # Writing agents with harness This guide walks you through building agents on top of `harness`. It assumes -you've read [`README.md`](./README.md) and have a Go 1.25+ project that depends +you've read [`README.md`](./README.md) and have a Go 1.26+ project that depends on `github.com/sausheong/harness`. > Two complete examples ship in [`examples/`](./examples) — `minimal/` (file + diff --git a/go.mod b/go.mod index 30b321b..1f8ea54 100644 --- a/go.mod +++ b/go.mod @@ -1,10 +1,11 @@ module github.com/sausheong/harness -go 1.25.1 +go 1.26.0 require ( github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0 github.com/anthropics/anthropic-sdk-go v1.35.0 + github.com/browserbase/stagehand/packages/sdk-go/v4 v4.1.0 github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 github.com/chromedp/chromedp v0.14.2 github.com/modelcontextprotocol/go-sdk v1.5.0 @@ -21,8 +22,11 @@ require ( cloud.google.com/go/auth v0.9.3 // indirect cloud.google.com/go/compute/metadata v0.9.0 // indirect github.com/JohannesKaufmann/dom v0.2.0 // indirect + github.com/bahlo/generic-list-go v0.2.0 // indirect + github.com/buger/jsonparser v1.1.2 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/chromedp/sysutil v1.1.0 // indirect + github.com/coder/websocket v1.8.13 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect github.com/gobwas/httphead v0.1.0 // indirect @@ -34,6 +38,8 @@ require ( github.com/google/s2a-go v0.1.8 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect github.com/gorilla/websocket v1.5.3 // indirect + github.com/invopop/jsonschema v0.14.0 // indirect + github.com/pb33f/ordered-map/v2 v2.3.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/segmentio/asm v1.1.3 // indirect github.com/segmentio/encoding v0.5.4 // indirect @@ -44,7 +50,9 @@ require ( github.com/yosida95/uritemplate/v3 v3.0.2 // indirect go.opencensus.io v0.24.0 // indirect go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect + go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect golang.org/x/crypto v0.49.0 // indirect + golang.org/x/mod v0.38.0 // indirect golang.org/x/net v0.52.0 // indirect golang.org/x/oauth2 v0.35.0 // indirect golang.org/x/sync v0.20.0 // indirect diff --git a/go.sum b/go.sum index b34fd64..cf3bc56 100644 --- a/go.sum +++ b/go.sum @@ -12,6 +12,12 @@ github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0 h1:mklaPbT4f/EiDr1Q+zPrEt github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0/go.mod h1:D56Cl9r8M5i3UwAchE+LlLc5hPN3kJtdZNVJn06lSHU= github.com/anthropics/anthropic-sdk-go v1.35.0 h1:W6K8mIkD1zIU0VUPMuokWONUvdlt2C//b11Zr6v5Oz4= github.com/anthropics/anthropic-sdk-go v1.35.0/go.mod h1:dSIO7kSrOI7MA4fE6RRVaw8tyWP7HNQU5/H/KS4cax8= +github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk= +github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= +github.com/browserbase/stagehand/packages/sdk-go/v4 v4.1.0 h1:XELhAEkPJlyjirc1aWPhd0n+ZdFP0U+wRWamGRD05K0= +github.com/browserbase/stagehand/packages/sdk-go/v4 v4.1.0/go.mod h1:Z4qkSeN4whiyoYk+jqKbwYbUPu16JgmvEZWtiiaXyqY= +github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk= +github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= @@ -23,6 +29,8 @@ github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipw github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE= +github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -81,12 +89,16 @@ github.com/googleapis/enterprise-certificate-proxy v0.3.4 h1:XYIDZApgAnrN1c855gT github.com/googleapis/enterprise-certificate-proxy v0.3.4/go.mod h1:YKe7cfqYXjKGpGvmSg28/fFvhNzinZQm8DGnaburhGA= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg= +github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I= github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo= github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs= github.com/modelcontextprotocol/go-sdk v1.5.0 h1:CHU0FIX9kpueNkxuYtfYQn1Z0slhFzBZuq+x6IiblIU= github.com/modelcontextprotocol/go-sdk v1.5.0/go.mod h1:gggDIhoemhWs3BGkGwd1umzEXCEMMvAnhTrnbXJKKKA= github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw= github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0= +github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY= +github.com/pb33f/ordered-map/v2 v2.3.1/go.mod h1:qxFQgd0PkVUtOMCkTapqotNgzRhMPL7VvaHKbd1HnmQ= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -136,6 +148,8 @@ go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfC go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A= go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= +go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s= +go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4= @@ -144,6 +158,8 @@ golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= +golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -176,8 +192,8 @@ golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= -golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= diff --git a/tools/stagehand/generate.go b/tools/stagehand/generate.go new file mode 100644 index 0000000..a348300 --- /dev/null +++ b/tools/stagehand/generate.go @@ -0,0 +1,328 @@ +package stagehand + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "strings" + + sh "github.com/browserbase/stagehand/packages/sdk-go/v4" + "github.com/sausheong/harness/llm" +) + +const ( + // generateMaxTokens bounds each inference call Stagehand makes. act/observe + // return short action lists; extract can return larger tables, so this is + // generous relative to typical responses. + generateMaxTokens = 8192 + // structuredToolName is the synthetic tool the model is forced to call for + // structured output. Harness providers have no portable response_format + // knob, but every provider supports tool calls whose input is validated + // against a JSON Schema — the tool input IS the structured result. + structuredToolName = "respond" +) + +// NewGenerateFunc adapts a harness LLMProvider to Stagehand's LLMGenerateFunc +// so Stagehand's internal inference (act, observe, extract) runs through the +// same provider — and the same usage observers and admission guards — as the +// agent itself, instead of a separately configured model and API key. +// +// Structured requests (extract, and act/observe's action selection) are +// served by forcing a single tool call whose parameters are the requested +// schema. Message requests pass Stagehand's tools through unchanged. +func NewGenerateFunc(provider llm.LLMProvider, model string) sh.LLMGenerateFunc { + return func(ctx context.Context, params sh.LLMGenerateParams) (sh.LLMGenerateResult, error) { + if provider == nil { + return sh.LLMGenerateResult{}, errors.New("stagehand: no LLM provider configured") + } + if structured, ok := params.AsStructured(); ok { + return generateStructured(ctx, provider, model, structured) + } + if message, ok := params.AsMessage(); ok { + return generateMessage(ctx, provider, model, message) + } + return sh.LLMGenerateResult{}, errors.New("stagehand: unsupported generate params") + } +} + +func generateStructured(ctx context.Context, provider llm.LLMProvider, model string, p sh.LLMStructuredGenerateParams) (sh.LLMGenerateResult, error) { + messages, err := toHarnessMessages(p.Messages) + if err != nil { + return sh.LLMGenerateResult{}, err + } + description := "Return the result. The input must match the requested schema exactly." + if p.ResponseFormat.Description != nil && *p.ResponseFormat.Description != "" { + description = *p.ResponseFormat.Description + } + tools, _ := provider.NormalizeToolSchema([]llm.ToolDef{{ + Name: structuredToolName, + Description: description, + Parameters: stripSchemaKeyword(p.ResponseFormat.Schema), + }}) + system := deref(p.SystemPrompt) + instruction := fmt.Sprintf("Respond ONLY by calling the %q tool exactly once. Do not reply with plain text.", structuredToolName) + if system != "" { + system += "\n\n" + instruction + } else { + system = instruction + } + req := llm.ChatRequest{ + Model: model, + Messages: messages, + Tools: tools, + MaxTokens: generateMaxTokens, + SystemPrompt: system, + } + if p.Temperature != nil { + req.Temperature, req.TemperatureSet = *p.Temperature, true + } + out, err := collect(ctx, provider, req) + if err != nil { + return sh.LLMGenerateResult{}, err + } + + var structured json.RawMessage + for _, tc := range out.toolCalls { + if tc.Name == structuredToolName { + structured = tc.Input + break + } + } + if structured == nil { + // Some models answer in text despite the instruction. Accept a bare + // (optionally fenced) JSON object rather than failing the whole act. + structured = jsonFromText(out.text) + } + if structured == nil { + return sh.LLMGenerateResult{}, fmt.Errorf("stagehand: model returned no structured output (stop reason %q)", out.stopReason) + } + return sh.StructuredGenerateResult(sh.LLMStructuredGenerateResult{ + Role: sh.LLMRoleAssistant, + Content: sh.LLMMessageContent{sh.TextContentBlock(sh.LLMTextContent{Text: string(structured)})}, + StopReason: stringPtr(out.stopReason), + Usage: out.usage, + StructuredContent: structured, + }), nil +} + +func generateMessage(ctx context.Context, provider llm.LLMProvider, model string, p sh.LLMMessageGenerateParams) (sh.LLMGenerateResult, error) { + messages, err := toHarnessMessages(p.Messages) + if err != nil { + return sh.LLMGenerateResult{}, err + } + req := llm.ChatRequest{ + Model: model, + Messages: messages, + MaxTokens: generateMaxTokens, + SystemPrompt: deref(p.SystemPrompt), + } + if p.Temperature != nil { + req.Temperature, req.TemperatureSet = *p.Temperature, true + } + // ChatRequest has no tool_choice field: "none" is honoured by sending no + // tools; "auto" and "required" both send them and let the model decide. + if !(p.ToolChoice != nil && p.ToolChoice.Mode != nil && *p.ToolChoice.Mode == sh.LLMToolChoiceModeNone) { + defs := make([]llm.ToolDef, 0, len(p.Tools)) + for _, t := range p.Tools { + schema, err := json.Marshal(t.InputSchema) + if err != nil { + return sh.LLMGenerateResult{}, fmt.Errorf("stagehand: encode schema for tool %q: %w", t.Name, err) + } + defs = append(defs, llm.ToolDef{Name: t.Name, Description: deref(t.Description), Parameters: stripSchemaKeyword(schema)}) + } + if len(defs) > 0 { + req.Tools, _ = provider.NormalizeToolSchema(defs) + } + } + out, err := collect(ctx, provider, req) + if err != nil { + return sh.LLMGenerateResult{}, err + } + + content := sh.LLMMessageContent{} + if out.text != "" { + content = append(content, sh.TextContentBlock(sh.LLMTextContent{Text: out.text})) + } + for _, tc := range out.toolCalls { + input := sh.LLMToolUseContentInput{} + if len(tc.Input) > 0 { + if err := json.Unmarshal(tc.Input, &input); err != nil { + return sh.LLMGenerateResult{}, fmt.Errorf("stagehand: decode tool call %q input: %w", tc.Name, err) + } + } + content = append(content, sh.ToolUseContentBlock(sh.LLMToolUseContent{ID: tc.ID, Name: tc.Name, Input: input})) + } + stop := out.stopReason + if len(out.toolCalls) > 0 { + stop = "tool_use" + } + return sh.MessageGenerateResult(sh.LLMMessageGenerateResult{ + Role: sh.LLMRoleAssistant, + Content: content, + StopReason: stringPtr(stop), + Usage: out.usage, + }), nil +} + +// toHarnessMessages flattens Stagehand's block-structured messages into +// harness messages. Tool results become separate "tool" role messages, which +// is how the harness providers expect them. +func toHarnessMessages(in []sh.LLMMessage) ([]llm.Message, error) { + out := make([]llm.Message, 0, len(in)) + for _, m := range in { + msg := llm.Message{Role: string(m.Role)} + var text []string + var toolResults []llm.Message + for _, block := range m.Content { + if t, ok := block.AsText(); ok { + text = append(text, t.Text) + } else if img, ok := block.AsImage(); ok { + decoded, err := decodeImage(img) + if err != nil { + return nil, err + } + msg.Images = append(msg.Images, decoded) + } else if tu, ok := block.AsToolUse(); ok { + input, err := json.Marshal(tu.Input) + if err != nil { + return nil, fmt.Errorf("stagehand: encode tool use %q: %w", tu.Name, err) + } + msg.ToolCalls = append(msg.ToolCalls, llm.ToolCall{ID: tu.ID, Name: tu.Name, Input: input}) + } else if tr, ok := block.AsToolResult(); ok { + result := llm.Message{Role: "tool", ToolCallID: tr.ToolUseID, IsError: tr.IsError != nil && *tr.IsError} + var parts []string + for _, rb := range tr.Content { + if t, ok := rb.AsText(); ok { + parts = append(parts, t.Text) + } else if img, ok := rb.AsImage(); ok { + decoded, err := decodeImage(img) + if err != nil { + return nil, err + } + result.Images = append(result.Images, decoded) + } + } + result.Content = strings.Join(parts, "\n") + toolResults = append(toolResults, result) + } + } + msg.Content = strings.Join(text, "\n") + if msg.Content != "" || len(msg.Images) > 0 || len(msg.ToolCalls) > 0 { + out = append(out, msg) + } + out = append(out, toolResults...) + } + return out, nil +} + +func decodeImage(img sh.LLMImageContent) (llm.ImageContent, error) { + data := img.Data + // Accept data URLs as well as bare base64. + if i := strings.Index(data, ";base64,"); strings.HasPrefix(data, "data:") && i >= 0 { + data = data[i+len(";base64,"):] + } + raw, err := base64.StdEncoding.DecodeString(data) + if err != nil { + return llm.ImageContent{}, fmt.Errorf("stagehand: decode image: %w", err) + } + return llm.ImageContent{MimeType: img.MIMEType, Data: raw}, nil +} + +type collected struct { + text string + toolCalls []llm.ToolCall + stopReason string + usage *sh.LLMUsage +} + +// collect drains one provider stream into a single response. +func collect(ctx context.Context, provider llm.LLMProvider, req llm.ChatRequest) (collected, error) { + stream, err := llm.ObserveChat(ctx, req, llm.CallGeneration, provider.ChatStream) + if err != nil { + return collected{}, fmt.Errorf("stagehand: chat stream: %w", err) + } + var out collected + var sb strings.Builder + for ev := range stream { + switch ev.Type { + case llm.EventTextDelta: + sb.WriteString(ev.Text) + case llm.EventToolCallDone: + if ev.ToolCall != nil { + out.toolCalls = append(out.toolCalls, *ev.ToolCall) + } + case llm.EventDone: + out.stopReason = ev.StopReason + if ev.Usage != nil { + out.usage = &sh.LLMUsage{ + InputTokens: ev.Usage.InputTokens, + OutputTokens: ev.Usage.OutputTokens, + TotalTokens: ev.Usage.InputTokens + ev.Usage.OutputTokens, + } + if ev.Usage.CacheReadInputTokens > 0 { + cached := ev.Usage.CacheReadInputTokens + out.usage.CachedInputTokens = &cached + } + } + case llm.EventError: + return collected{}, fmt.Errorf("stagehand: stream error: %w", ev.Error) + } + } + if err := ctx.Err(); err != nil { + return collected{}, err + } + if out.stopReason == llm.StopReasonRefusal { + return collected{}, errors.New("stagehand: model refused the request") + } + out.text = sb.String() + return out, nil +} + +// stripSchemaKeyword removes a top-level "$schema" key. Stagehand's schemas +// are generated by a JSON Schema reflector that emits it, and several +// provider tool-schema validators reject unknown top-level keywords. +func stripSchemaKeyword(schema json.RawMessage) json.RawMessage { + var m map[string]json.RawMessage + if err := json.Unmarshal(schema, &m); err != nil { + return schema + } + if _, ok := m["$schema"]; !ok { + return schema + } + delete(m, "$schema") + out, err := json.Marshal(m) + if err != nil { + return schema + } + return out +} + +// jsonFromText returns the JSON object in s, tolerating a surrounding +// markdown code fence. Returns nil when s holds no valid object. +func jsonFromText(s string) json.RawMessage { + s = strings.TrimSpace(s) + s = strings.TrimPrefix(s, "```json") + s = strings.TrimPrefix(s, "```") + s = strings.TrimSuffix(s, "```") + s = strings.TrimSpace(s) + if !strings.HasPrefix(s, "{") || !json.Valid([]byte(s)) { + return nil + } + return json.RawMessage(s) +} + +func deref(s *string) string { + if s == nil { + return "" + } + return *s +} + +func stringPtr(s string) *string { + if s == "" { + return nil + } + return &s +} diff --git a/tools/stagehand/generate_test.go b/tools/stagehand/generate_test.go new file mode 100644 index 0000000..0bb56d8 --- /dev/null +++ b/tools/stagehand/generate_test.go @@ -0,0 +1,211 @@ +package stagehand + +import ( + "context" + "encoding/base64" + "encoding/json" + "strings" + "testing" + + sh "github.com/browserbase/stagehand/packages/sdk-go/v4" + "github.com/sausheong/harness/llm" + "github.com/sausheong/harness/llm/llmtest" +) + +// scripted emits a fixed event sequence and records the request. +type scripted struct { + llmtest.Base + events []llm.ChatEvent + got llm.ChatRequest +} + +func (s *scripted) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) { + s.got = req + ch := make(chan llm.ChatEvent, len(s.events)) + for _, ev := range s.events { + ch <- ev + } + close(ch) + return ch, nil +} + +func userText(text string) sh.LLMMessage { + return sh.LLMMessage{Role: sh.LLMRoleUser, Content: sh.LLMMessageContent{sh.TextContentBlock(sh.LLMTextContent{Text: text})}} +} + +func TestGenerateStructuredUsesForcedToolCall(t *testing.T) { + p := &scripted{events: []llm.ChatEvent{ + {Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "t1", Name: structuredToolName, Input: json.RawMessage(`{"title":"Hello"}`)}}, + {Type: llm.EventDone, StopReason: "tool_use", Usage: &llm.Usage{InputTokens: 10, OutputTokens: 5}}, + }} + sys := "extract things" + params := sh.StructuredGenerateParams(sh.LLMStructuredGenerateParams{ + Messages: []sh.LLMMessage{userText("page content")}, + SystemPrompt: &sys, + ResponseFormat: sh.LLMJSONSchemaResponseFormat{ + Name: "extraction", + Schema: json.RawMessage(`{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"title":{"type":"string"}}}`), + }, + }) + + res, err := NewGenerateFunc(p, "m1")(context.Background(), params) + if err != nil { + t.Fatal(err) + } + structured, ok := res.AsStructured() + if !ok { + t.Fatalf("want structured result, got %#v", res) + } + if string(structured.StructuredContent) != `{"title":"Hello"}` { + t.Errorf("structured content = %s", structured.StructuredContent) + } + if structured.Usage == nil || structured.Usage.TotalTokens != 15 { + t.Errorf("usage = %+v", structured.Usage) + } + + if p.got.Model != "m1" { + t.Errorf("model = %q", p.got.Model) + } + if len(p.got.Tools) != 1 || p.got.Tools[0].Name != structuredToolName { + t.Fatalf("tools = %+v", p.got.Tools) + } + if strings.Contains(string(p.got.Tools[0].Parameters), "$schema") { + t.Errorf("$schema not stripped: %s", p.got.Tools[0].Parameters) + } + if !strings.HasPrefix(p.got.SystemPrompt, "extract things") || !strings.Contains(p.got.SystemPrompt, structuredToolName) { + t.Errorf("system prompt = %q", p.got.SystemPrompt) + } +} + +func TestGenerateStructuredFallsBackToFencedJSON(t *testing.T) { + p := &scripted{events: []llm.ChatEvent{ + {Type: llm.EventTextDelta, Text: "```json\n{\"a\":1}\n```"}, + {Type: llm.EventDone, StopReason: "end_turn"}, + }} + params := sh.StructuredGenerateParams(sh.LLMStructuredGenerateParams{ + Messages: []sh.LLMMessage{userText("x")}, + ResponseFormat: sh.LLMJSONSchemaResponseFormat{Name: "r", Schema: json.RawMessage(`{"type":"object"}`)}, + }) + res, err := NewGenerateFunc(p, "m")(context.Background(), params) + if err != nil { + t.Fatal(err) + } + structured, _ := res.AsStructured() + if string(structured.StructuredContent) != `{"a":1}` { + t.Errorf("structured content = %s", structured.StructuredContent) + } +} + +func TestGenerateStructuredErrorsWithoutOutput(t *testing.T) { + p := &scripted{events: []llm.ChatEvent{ + {Type: llm.EventTextDelta, Text: "I can't find that."}, + {Type: llm.EventDone, StopReason: "end_turn"}, + }} + params := sh.StructuredGenerateParams(sh.LLMStructuredGenerateParams{ + Messages: []sh.LLMMessage{userText("x")}, + ResponseFormat: sh.LLMJSONSchemaResponseFormat{Name: "r", Schema: json.RawMessage(`{"type":"object"}`)}, + }) + if _, err := NewGenerateFunc(p, "m")(context.Background(), params); err == nil { + t.Fatal("want error for missing structured output") + } +} + +func TestGenerateMessageMapsToolsAndHistory(t *testing.T) { + p := &scripted{events: []llm.ChatEvent{ + {Type: llm.EventTextDelta, Text: "clicking"}, + {Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "c2", Name: "click", Input: json.RawMessage(`{"selector":"#go"}`)}}, + {Type: llm.EventDone, StopReason: "tool_use"}, + }} + desc := "Click an element" + png := base64.StdEncoding.EncodeToString([]byte("fakepng")) + isErr := true + params := sh.MessageGenerateParams(sh.LLMMessageGenerateParams{ + Messages: []sh.LLMMessage{ + {Role: sh.LLMRoleUser, Content: sh.LLMMessageContent{ + sh.TextContentBlock(sh.LLMTextContent{Text: "do it"}), + sh.ImageContentBlock(sh.LLMImageContent{Data: "data:image/png;base64," + png, MIMEType: "image/png"}), + }}, + {Role: sh.LLMRoleAssistant, Content: sh.LLMMessageContent{ + sh.ToolUseContentBlock(sh.LLMToolUseContent{ID: "c1", Name: "click", Input: sh.LLMToolUseContentInput{"selector": json.RawMessage(`"#a"`)}}), + }}, + {Role: sh.LLMRoleUser, Content: sh.LLMMessageContent{ + sh.ToolResultContentBlock(sh.LLMToolResultContent{ToolUseID: "c1", IsError: &isErr, Content: []sh.LLMToolResultContentBlock{ + sh.ToolResultTextBlock(sh.LLMTextContent{Text: "not found"}), + }}), + }}, + }, + Tools: []sh.LLMClientTool{{Name: "click", Description: &desc, InputSchema: sh.LLMToolJSON{Type: "object"}}}, + }) + + res, err := NewGenerateFunc(p, "m")(context.Background(), params) + if err != nil { + t.Fatal(err) + } + + msgs := p.got.Messages + if len(msgs) != 3 { + t.Fatalf("messages = %+v", msgs) + } + if msgs[0].Role != "user" || msgs[0].Content != "do it" || len(msgs[0].Images) != 1 || string(msgs[0].Images[0].Data) != "fakepng" { + t.Errorf("user message = %+v", msgs[0]) + } + if msgs[1].Role != "assistant" || len(msgs[1].ToolCalls) != 1 || msgs[1].ToolCalls[0].ID != "c1" { + t.Errorf("assistant message = %+v", msgs[1]) + } + if msgs[2].Role != "tool" || msgs[2].ToolCallID != "c1" || !msgs[2].IsError || msgs[2].Content != "not found" { + t.Errorf("tool result message = %+v", msgs[2]) + } + if len(p.got.Tools) != 1 || p.got.Tools[0].Name != "click" || p.got.Tools[0].Description != desc { + t.Errorf("tools = %+v", p.got.Tools) + } + + message, ok := res.AsMessage() + if !ok { + t.Fatalf("want message result, got %#v", res) + } + if message.StopReason == nil || *message.StopReason != "tool_use" { + t.Errorf("stop reason = %v", message.StopReason) + } + if len(message.Content) != 2 { + t.Fatalf("content = %+v", message.Content) + } + if txt, ok := message.Content[0].AsText(); !ok || txt.Text != "clicking" { + t.Errorf("content[0] = %+v", message.Content[0]) + } + tu, ok := message.Content[1].AsToolUse() + if !ok || tu.ID != "c2" || string(tu.Input["selector"]) != `"#go"` { + t.Errorf("content[1] = %+v", message.Content[1]) + } + // The result must survive the SDK's own JSON encoding (it crosses an RPC boundary). + if _, err := json.Marshal(res); err != nil { + t.Errorf("marshal result: %v", err) + } +} + +func TestGenerateMessageToolChoiceNoneSendsNoTools(t *testing.T) { + p := &scripted{events: []llm.ChatEvent{{Type: llm.EventTextDelta, Text: "ok"}, {Type: llm.EventDone}}} + none := sh.LLMToolChoiceModeNone + params := sh.MessageGenerateParams(sh.LLMMessageGenerateParams{ + Messages: []sh.LLMMessage{userText("hi")}, + Tools: []sh.LLMClientTool{{Name: "click", InputSchema: sh.LLMToolJSON{Type: "object"}}}, + ToolChoice: &sh.LLMToolChoice{Mode: &none}, + }) + if _, err := NewGenerateFunc(p, "m")(context.Background(), params); err != nil { + t.Fatal(err) + } + if len(p.got.Tools) != 0 { + t.Errorf("tools sent despite tool_choice none: %+v", p.got.Tools) + } +} + +func TestGenerateSurfacesRefusalAndStreamErrors(t *testing.T) { + params := sh.MessageGenerateParams(sh.LLMMessageGenerateParams{Messages: []sh.LLMMessage{userText("hi")}}) + refusal := &scripted{events: []llm.ChatEvent{{Type: llm.EventDone, StopReason: llm.StopReasonRefusal}}} + if _, err := NewGenerateFunc(refusal, "m")(context.Background(), params); err == nil { + t.Error("want error on refusal") + } + stub := &llmtest.Stub{ChatErr: context.DeadlineExceeded} + if _, err := NewGenerateFunc(stub, "m")(context.Background(), params); err == nil { + t.Error("want error on chat failure") + } +} diff --git a/tools/stagehand/stagehand.go b/tools/stagehand/stagehand.go new file mode 100644 index 0000000..849f753 --- /dev/null +++ b/tools/stagehand/stagehand.go @@ -0,0 +1,535 @@ +// Package stagehand provides a browser tool built on Stagehand +// (github.com/browserbase/stagehand), which drives the browser with +// natural-language instructions — "click the sign in button", "extract every +// invoice in the table" — instead of CSS selectors. Stagehand's own inference +// runs through the agent's harness LLMProvider (see NewGenerateFunc). +// +// Two backends: a local Chrome launched on this machine (default), or a +// Browserbase cloud browser when Config.BrowserbaseAPIKey is set. +package stagehand + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "sync" + "time" + + sh "github.com/browserbase/stagehand/packages/sdk-go/v4" + "github.com/sausheong/harness/llm" + "github.com/sausheong/harness/tool" + "github.com/sausheong/harness/tools/web" +) + +const ( + // callTimeout bounds one tool call. act/extract each make one or more + // LLM round trips on top of browser work, so this is looser than a + // plain CDP action budget. + callTimeout = 180 * time.Second + // launchTimeout bounds browser launch + Stagehand init. + launchTimeout = 90 * time.Second + // closeTimeout bounds teardown so a wedged browser can't hang shutdown. + closeTimeout = 15 * time.Second + + defaultViewportW = 1440 + defaultViewportH = 900 + maxTextOutput = 100_000 + + sessionIdleTimeout = 10 * time.Minute + sessionMaxCount = 5 + janitorInterval = 1 * time.Minute +) + +// hostResolverRules mirrors tools/browser: it makes a *local* Chrome fail DNS +// for localhost and private ranges so in-page fetch()/XHR can't reach +// cloud-metadata endpoints or local services. The Go-side +// ValidateURLNotInternal check only covers the top-level URL. Browserbase +// browsers run remotely and can't reach this machine's network anyway. +const hostResolverRules = "MAP localhost ~NOTFOUND," + + "MAP *.localhost ~NOTFOUND," + + "MAP 127.0.0.0/8 ~NOTFOUND," + + "MAP 10.0.0.0/8 ~NOTFOUND," + + "MAP 172.16.0.0/12 ~NOTFOUND," + + "MAP 169.254.0.0/16 ~NOTFOUND," + + "MAP 192.168.0.0/16 ~NOTFOUND," + + "MAP [::1] ~NOTFOUND" + +// Config configures a StagehandTool. +type Config struct { + // Provider and Model serve Stagehand's internal inference. Required. + Provider llm.LLMProvider + Model string + + // BrowserbaseAPIKey selects the Browserbase cloud backend when non-empty; + // otherwise a local Chrome is launched. The tool never reads the + // environment itself — callers opt in explicitly, e.g. + // os.Getenv("BROWSERBASE_API_KEY"). + BrowserbaseAPIKey string + + // Headful shows the local Chrome window. Ignored for Browserbase. + Headful bool + // ChromePath overrides the local Chrome executable. Empty = auto-detect. + ChromePath string +} + +// session is one browser + Stagehand client pair. Calls into the same +// session serialize via mu: a Stagehand client drives one active page and +// interleaved act/navigate calls would race on it. +type session struct { + mu sync.Mutex + browser *sh.Browser + client *sh.Stagehand + lastUsed time.Time +} + +// StagehandTool is an AI-driven browser tool. +// +// Like tools/browser it has two execution modes: +// - Ephemeral (no "session"): each call launches a browser, runs the +// action, and tears down. Requires "url". +// - Persistent ("session"): the named browser persists across calls so +// cookies, auth and page state carry over. Sessions auto-close after +// sessionIdleTimeout, or on "action": "close". +type StagehandTool struct { + cfg Config + + // launch is the browser+client factory; tests replace it. + launch func(ctx context.Context) (*session, error) + + mu sync.Mutex + sessions map[string]*session + stopJanitor chan struct{} +} + +type stagehandInput struct { + Action string `json:"action"` + Session string `json:"session,omitempty"` + URL string `json:"url,omitempty"` + Instruction string `json:"instruction,omitempty"` + Schema json.RawMessage `json:"schema,omitempty"` + FullPage bool `json:"full_page,omitempty"` +} + +// NewStagehandTool validates cfg and returns a tool. No browser is launched +// until the first call. +func NewStagehandTool(cfg Config) (*StagehandTool, error) { + if cfg.Provider == nil { + return nil, errors.New("stagehand: Config.Provider is required") + } + if cfg.Model == "" { + return nil, errors.New("stagehand: Config.Model is required") + } + t := &StagehandTool{cfg: cfg} + t.launch = t.launchSession + return t, nil +} + +func (t *StagehandTool) Name() string { return "stagehand" } + +func (t *StagehandTool) Description() string { + return `Control a web browser with natural-language instructions (Stagehand). Prefer this over the "browser" tool when you don't know the page's CSS selectors: describe WHAT to do and Stagehand finds the elements. + +SESSIONS — each call without "session" uses a fresh browser that is closed afterwards, so it must include "url". For any multi-step flow (navigate, then act, then extract), pass the SAME "session": "