Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d47a71f779 | ||
|
|
62f3424f30 | ||
|
|
a1f34cce4c | ||
|
|
9a013f6f4b | ||
|
|
1e5b6599bb | ||
|
|
3ca0994437 |
No files matched your search
@@ -5,7 +5,7 @@ streaming agent loop, tool registry, session storage, compaction, and
|
|||||||
token budgeting needed to run a multi-provider agent in production. BYO
|
token budgeting needed to run a multi-provider agent in production. BYO
|
||||||
concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins.
|
concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins.
|
||||||
|
|
||||||
> **Status: v0.4.0.** Latest tagged release. The `runtime` API
|
> **Status: v0.4.2.** Latest tagged release. The `runtime` API
|
||||||
> surface may still shift in the v0.x line — pin your version.
|
> surface may still shift in the v0.x line — pin your version.
|
||||||
|
|
||||||
## Why Harness
|
## Why Harness
|
||||||
@@ -26,6 +26,29 @@ opinions about how your agents should be deployed. There is no
|
|||||||
`harness` binary. You import packages, compose a `Runtime`, and call
|
`harness` binary. You import packages, compose a `Runtime`, and call
|
||||||
`rt.Run(ctx, msg, nil)`.
|
`rt.Run(ctx, msg, nil)`.
|
||||||
|
|
||||||
|
## What's in v0.4.2
|
||||||
|
|
||||||
|
[v0.4.2](https://github.com/sausheong/harness/releases/tag/v0.4.2)
|
||||||
|
improves response handling and tool visibility for applications such as Hand:
|
||||||
|
|
||||||
|
- **Empty answers fail clearly.** `Runtime.Run` retries a response with no text
|
||||||
|
or tool calls once, subject to existing budgets and cancellation. It keeps
|
||||||
|
the same output allowance and does not replay tools. If no answer arrives,
|
||||||
|
the run reports an error. `RunTurn` reports the error directly; its caller
|
||||||
|
controls retries.
|
||||||
|
- **Output limits remain visible.** Answers stopped by `length` or `max_tokens`
|
||||||
|
are reported as incomplete rather than successful. The OpenAI-compatible
|
||||||
|
provider preserves finish reasons and trailing usage records, and does not
|
||||||
|
dispatch partial tool arguments from an output-truncated response.
|
||||||
|
- **Truncated summaries preserve history.** Compaction rejects a summary that
|
||||||
|
reaches its output limit, retaining the original conversation.
|
||||||
|
- **Complete tool arguments before execution.** `EventToolCallReady` carries
|
||||||
|
the complete tool call so a host can preview a command before it runs.
|
||||||
|
|
||||||
|
This includes the v0.4.1 fixes for repeated stream finishes and preservation
|
||||||
|
of cancellation causes. See [releases](https://github.com/sausheong/harness/releases)
|
||||||
|
for version-by-version notes.
|
||||||
|
|
||||||
## What's in v0.4.0
|
## What's in v0.4.0
|
||||||
|
|
||||||
v0.4.0 adds the operational controls needed by a production coding
|
v0.4.0 adds the operational controls needed by a production coding
|
||||||
@@ -109,9 +132,9 @@ a lot. The package is optimized for the use cases above, not these.
|
|||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- **Go 1.25.1 or newer.** The module declares `go 1.25.1` and uses
|
- **Go 1.26 or newer.** The module declares `go 1.26.0`, required by
|
||||||
`iter.Seq` from `iter` (Go 1.23+) plus a few stdlib calls that
|
the Stagehand SDK that `tools/stagehand` depends on. With the default
|
||||||
hardened in 1.25. Older toolchains will fail at `go build`.
|
`GOTOOLCHAIN=auto`, an older local Go downloads 1.26 automatically.
|
||||||
- **An LLM API key**, depending on which provider(s) you wire in:
|
- **An LLM API key**, depending on which provider(s) you wire in:
|
||||||
`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, Google ADC for Gemini, or a
|
`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, Google ADC for Gemini, or a
|
||||||
LiteLLM/OpenRouter key for those aggregators. For local models
|
LiteLLM/OpenRouter key for those aggregators. For local models
|
||||||
@@ -160,6 +183,8 @@ github.com/sausheong/harness/
|
|||||||
├── bash/ # bash (with ExecPolicy: deny | allowlist | full)
|
├── bash/ # bash (with ExecPolicy: deny | allowlist | full)
|
||||||
├── web/ # web_fetch, web_search, ssrf guard
|
├── web/ # web_fetch, web_search, ssrf guard
|
||||||
├── browser/ # chromedp wrapper with per-session reuse
|
├── 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
|
├── mcp/ # Connect to external MCP servers; adapt their tools
|
||||||
└── todo/ # todo_write
|
└── todo/ # todo_write
|
||||||
```
|
```
|
||||||
@@ -311,8 +336,10 @@ Deliberately not in scope:
|
|||||||
## Design notes
|
## Design notes
|
||||||
|
|
||||||
- **Streaming-first.** The loop yields `EventTextDelta`,
|
- **Streaming-first.** The loop yields `EventTextDelta`,
|
||||||
`EventToolCallStart`, `EventToolResult`, `EventDone`, and friends
|
`EventToolCallStart`, `EventToolCallReady`, `EventToolResult`,
|
||||||
through a `<-chan ChatEvent`. There is no buffered "give me the
|
`EventDone`, and friends through a `<-chan AgentEvent`.
|
||||||
|
Use `EventToolCallReady` for complete arguments; the start event may arrive
|
||||||
|
before arguments are available. There is no buffered "give me the
|
||||||
whole response" path — even the non-streaming fallback re-emits
|
whole response" path — even the non-streaming fallback re-emits
|
||||||
through the same channel.
|
through the same channel.
|
||||||
- **Prompt-cache discipline.** Tool definitions are sorted, system
|
- **Prompt-cache discipline.** Tool definitions are sorted, system
|
||||||
@@ -425,12 +452,12 @@ tests. See [`scripts/QUALIFICATION.md`](./scripts/QUALIFICATION.md).
|
|||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
`v0.4.0` is the latest tagged release. The v0.x line follows Go
|
`v0.4.2` is the latest tagged release. The v0.x line follows Go
|
||||||
module semver: minor bumps may break API, patch bumps are bug-fix
|
module semver: minor bumps may break API, patch bumps are bug-fix
|
||||||
only. Pin your dependency:
|
only. Pin your dependency:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go get github.com/sausheong/[email protected].0
|
go get github.com/sausheong/[email protected].2
|
||||||
```
|
```
|
||||||
|
|
||||||
Likely sources of v0.x churn before a v1.0.0:
|
Likely sources of v0.x churn before a v1.0.0:
|
||||||
|
|||||||
@@ -119,6 +119,7 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
|
|||||||
}
|
}
|
||||||
|
|
||||||
var sb strings.Builder
|
var sb strings.Builder
|
||||||
|
var terminalReason string
|
||||||
for ev := range stream {
|
for ev := range stream {
|
||||||
switch ev.Type {
|
switch ev.Type {
|
||||||
case llm.EventTextDelta:
|
case llm.EventTextDelta:
|
||||||
@@ -126,6 +127,8 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
|
|||||||
return "", errors.New("summariser response exceeds 256 KiB")
|
return "", errors.New("summariser response exceeds 256 KiB")
|
||||||
}
|
}
|
||||||
sb.WriteString(ev.Text)
|
sb.WriteString(ev.Text)
|
||||||
|
case llm.EventDone:
|
||||||
|
terminalReason = ev.StopReason
|
||||||
case llm.EventError:
|
case llm.EventError:
|
||||||
return "", fmt.Errorf("compaction: stream error: %w", ev.Error)
|
return "", fmt.Errorf("compaction: stream error: %w", ev.Error)
|
||||||
}
|
}
|
||||||
@@ -133,6 +136,9 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
|
|||||||
if err := callCtx.Err(); err != nil {
|
if err := callCtx.Err(); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
if terminalReason == "length" || terminalReason == "max_tokens" {
|
||||||
|
return "", errors.New("summariser reached its output limit; original history retained")
|
||||||
|
}
|
||||||
out := strings.TrimSpace(sb.String())
|
out := strings.TrimSpace(sb.String())
|
||||||
if out == "" {
|
if out == "" {
|
||||||
return "", ErrEmptySummary
|
return "", ErrEmptySummary
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package compaction
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/sausheong/harness/llm"
|
||||||
|
"github.com/sausheong/harness/llm/llmtest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type truncatedSummaryProvider struct{ llmtest.Base }
|
||||||
|
|
||||||
|
func (truncatedSummaryProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||||
|
ch := make(chan llm.ChatEvent, 2)
|
||||||
|
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Incomplete summary"}
|
||||||
|
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: "length"}
|
||||||
|
close(ch)
|
||||||
|
return ch, nil
|
||||||
|
}
|
||||||
|
func TestRejectTruncatedSummary(t *testing.T) {
|
||||||
|
s := Summarizer{Provider: truncatedSummaryProvider{}, Model: "fixture"}
|
||||||
|
out, err := s.callOnce(context.Background(), "history", "")
|
||||||
|
if err == nil || out != "" || !strings.Contains(err.Error(), "output limit") {
|
||||||
|
t.Fatalf("%q %v", out, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
# Writing agents with harness
|
# Writing agents with harness
|
||||||
|
|
||||||
This guide walks you through building agents on top of `harness`. It assumes
|
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`.
|
on `github.com/sausheong/harness`.
|
||||||
|
|
||||||
> Two complete examples ship in [`examples/`](./examples) — `minimal/` (file +
|
> Two complete examples ship in [`examples/`](./examples) — `minimal/` (file +
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
module github.com/sausheong/harness
|
module github.com/sausheong/harness
|
||||||
|
|
||||||
go 1.25.1
|
go 1.26.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0
|
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0
|
||||||
github.com/anthropics/anthropic-sdk-go v1.35.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/cdproto v0.0.0-20250724212937-08a3db8b4327
|
||||||
github.com/chromedp/chromedp v0.14.2
|
github.com/chromedp/chromedp v0.14.2
|
||||||
github.com/modelcontextprotocol/go-sdk v1.5.0
|
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/auth v0.9.3 // indirect
|
||||||
cloud.google.com/go/compute/metadata v0.9.0 // indirect
|
cloud.google.com/go/compute/metadata v0.9.0 // indirect
|
||||||
github.com/JohannesKaufmann/dom v0.2.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/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
github.com/chromedp/sysutil v1.1.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/davecgh/go-spew v1.1.1 // indirect
|
||||||
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect
|
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect
|
||||||
github.com/gobwas/httphead v0.1.0 // 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/google/s2a-go v0.1.8 // indirect
|
||||||
github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect
|
github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect
|
||||||
github.com/gorilla/websocket v1.5.3 // 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/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/segmentio/asm v1.1.3 // indirect
|
github.com/segmentio/asm v1.1.3 // indirect
|
||||||
github.com/segmentio/encoding v0.5.4 // indirect
|
github.com/segmentio/encoding v0.5.4 // indirect
|
||||||
@@ -44,7 +50,9 @@ require (
|
|||||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||||
go.opencensus.io v0.24.0 // indirect
|
go.opencensus.io v0.24.0 // indirect
|
||||||
go.opentelemetry.io/otel/sdk/metric v1.43.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/crypto v0.49.0 // indirect
|
||||||
|
golang.org/x/mod v0.38.0 // indirect
|
||||||
golang.org/x/net v0.52.0 // indirect
|
golang.org/x/net v0.52.0 // indirect
|
||||||
golang.org/x/oauth2 v0.35.0 // indirect
|
golang.org/x/oauth2 v0.35.0 // indirect
|
||||||
golang.org/x/sync v0.20.0 // indirect
|
golang.org/x/sync v0.20.0 // indirect
|
||||||
|
|||||||
@@ -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/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 h1:W6K8mIkD1zIU0VUPMuokWONUvdlt2C//b11Zr6v5Oz4=
|
||||||
github.com/anthropics/anthropic-sdk-go v1.35.0/go.mod h1:dSIO7kSrOI7MA4fE6RRVaw8tyWP7HNQU5/H/KS4cax8=
|
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/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 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
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/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
|
||||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
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/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.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 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
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/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 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
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 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo=
|
||||||
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
|
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 h1:CHU0FIX9kpueNkxuYtfYQn1Z0slhFzBZuq+x6IiblIU=
|
||||||
github.com/modelcontextprotocol/go-sdk v1.5.0/go.mod h1:gggDIhoemhWs3BGkGwd1umzEXCEMMvAnhTrnbXJKKKA=
|
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 h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
|
||||||
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
|
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 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
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=
|
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/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 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
|
||||||
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
|
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-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.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
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-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-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
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-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-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/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-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-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||||
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
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.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||||
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
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=
|
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 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||||
|
|||||||
+7
-3
@@ -22,10 +22,14 @@ const (
|
|||||||
EventThinkingBlock
|
EventThinkingBlock
|
||||||
)
|
)
|
||||||
|
|
||||||
// ImageContent holds image data for multimodal messages.
|
// ImageContent holds image data for multimodal messages. MimeType
|
||||||
|
// "application/pdf" is carried as a PDF document (not an image) by
|
||||||
|
// providers that support it (e.g. Anthropic emits a `document` block);
|
||||||
|
// providers without PDF support report a clear error or placeholder
|
||||||
|
// instead of silently mishandling the bytes.
|
||||||
type ImageContent struct {
|
type ImageContent struct {
|
||||||
MimeType string // "image/jpeg", "image/png", etc.
|
MimeType string // "image/jpeg", "image/png", "application/pdf", etc.
|
||||||
Data []byte // raw image bytes
|
Data []byte // raw bytes
|
||||||
}
|
}
|
||||||
|
|
||||||
// Message represents a conversation message.
|
// Message represents a conversation message.
|
||||||
|
|||||||
@@ -160,6 +160,16 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
|
|||||||
slog.Info("anthropic adaptive thinking",
|
slog.Info("anthropic adaptive thinking",
|
||||||
"model", model,
|
"model", model,
|
||||||
"effort", string(anthropicEffort(req.Reasoning)))
|
"effort", string(anthropicEffort(req.Reasoning)))
|
||||||
|
} else if anthropicRejectsDisabledThinking(model) {
|
||||||
|
// Opus 5.5 can't turn thinking off: {type:"disabled"} is a 400
|
||||||
|
// ("use thinking.type.adaptive and output_config.effort").
|
||||||
|
// Adaptive at low effort is the closest accepted "off".
|
||||||
|
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||||
|
OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{},
|
||||||
|
}
|
||||||
|
params.OutputConfig = anthropic.OutputConfigParam{
|
||||||
|
Effort: anthropic.OutputConfigEffortLow,
|
||||||
|
}
|
||||||
} else if anthropicThinksByDefault(model) {
|
} else if anthropicThinksByDefault(model) {
|
||||||
// Opus 5 and Sonnet 5 think by default when the thinking
|
// Opus 5 and Sonnet 5 think by default when the thinking
|
||||||
// param is omitted entirely (unlike Opus 4.7/4.8, Fable 5,
|
// param is omitted entirely (unlike Opus 4.7/4.8, Fable 5,
|
||||||
@@ -557,6 +567,13 @@ func anthropicThinksByDefault(model string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// anthropicRejectsDisabledThinking reports whether the model returns a 400
|
||||||
|
// for thinking {type:"disabled"}. Checked before anthropicThinksByDefault,
|
||||||
|
// whose "claude-opus-5" marker also matches Opus 5.5 IDs.
|
||||||
|
func anthropicRejectsDisabledThinking(model string) bool {
|
||||||
|
return strings.Contains(model, "claude-opus-5-5")
|
||||||
|
}
|
||||||
|
|
||||||
// anthropicEffort maps the unified ReasoningMode onto output_config.effort
|
// anthropicEffort maps the unified ReasoningMode onto output_config.effort
|
||||||
// for adaptive-thinking-only models.
|
// for adaptive-thinking-only models.
|
||||||
func anthropicEffort(mode llm.ReasoningMode) anthropic.OutputConfigEffort {
|
func anthropicEffort(mode llm.ReasoningMode) anthropic.OutputConfigEffort {
|
||||||
@@ -621,6 +638,10 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
|
|||||||
var blocks []anthropic.ContentBlockParamUnion
|
var blocks []anthropic.ContentBlockParamUnion
|
||||||
for _, img := range m.Images {
|
for _, img := range m.Images {
|
||||||
encoded := base64.StdEncoding.EncodeToString(img.Data)
|
encoded := base64.StdEncoding.EncodeToString(img.Data)
|
||||||
|
if img.MimeType == "application/pdf" {
|
||||||
|
blocks = append(blocks, anthropic.NewDocumentBlock(anthropic.Base64PDFSourceParam{Data: encoded}))
|
||||||
|
continue
|
||||||
|
}
|
||||||
blocks = append(blocks, anthropic.NewImageBlockBase64(img.MimeType, encoded))
|
blocks = append(blocks, anthropic.NewImageBlockBase64(img.MimeType, encoded))
|
||||||
}
|
}
|
||||||
if m.Content != "" {
|
if m.Content != "" {
|
||||||
@@ -694,6 +715,8 @@ func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion, cache *llm.
|
|||||||
block.OfToolResult.CacheControl = cc
|
block.OfToolResult.CacheControl = cc
|
||||||
case block.OfImage != nil:
|
case block.OfImage != nil:
|
||||||
block.OfImage.CacheControl = cc
|
block.OfImage.CacheControl = cc
|
||||||
|
case block.OfDocument != nil:
|
||||||
|
block.OfDocument.CacheControl = cc
|
||||||
case block.OfToolUse != nil:
|
case block.OfToolUse != nil:
|
||||||
block.OfToolUse.CacheControl = cc
|
block.OfToolUse.CacheControl = cc
|
||||||
}
|
}
|
||||||
@@ -709,6 +732,16 @@ func buildToolResultBlock(m llm.Message) anthropic.ContentBlockParamUnion {
|
|||||||
var content []anthropic.ToolResultBlockParamContentUnion
|
var content []anthropic.ToolResultBlockParamContentUnion
|
||||||
for _, img := range m.Images {
|
for _, img := range m.Images {
|
||||||
encoded := base64.StdEncoding.EncodeToString(img.Data)
|
encoded := base64.StdEncoding.EncodeToString(img.Data)
|
||||||
|
if img.MimeType == "application/pdf" {
|
||||||
|
content = append(content, anthropic.ToolResultBlockParamContentUnion{
|
||||||
|
OfDocument: &anthropic.DocumentBlockParam{
|
||||||
|
Source: anthropic.DocumentBlockParamSourceUnion{
|
||||||
|
OfBase64: &anthropic.Base64PDFSourceParam{Data: encoded},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
content = append(content, anthropic.ToolResultBlockParamContentUnion{
|
content = append(content, anthropic.ToolResultBlockParamContentUnion{
|
||||||
OfImage: &anthropic.ImageBlockParam{
|
OfImage: &anthropic.ImageBlockParam{
|
||||||
Source: anthropic.ImageBlockParamSourceUnion{
|
Source: anthropic.ImageBlockParamSourceUnion{
|
||||||
|
|||||||
@@ -221,6 +221,101 @@ func TestAnthropic_ToolResultsWithImages(t *testing.T) {
|
|||||||
assert.True(t, p3.IsError.Value)
|
assert.True(t, p3.IsError.Value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestAnthropic_ToolResultWithPDFAttachment verifies that a tool result
|
||||||
|
// carrying a PDF attachment (MimeType "application/pdf") emits a
|
||||||
|
// document block with media_type application/pdf and the base64 data,
|
||||||
|
// alongside a separate image attachment's own image block.
|
||||||
|
func TestAnthropic_ToolResultWithPDFAttachment(t *testing.T) {
|
||||||
|
pngBytes := []byte{0x89, 0x50, 0x4E, 0x47}
|
||||||
|
pdfBytes := []byte("%PDF-1.4 fake pdf bytes")
|
||||||
|
in := []llm.Message{
|
||||||
|
{
|
||||||
|
Role: "assistant",
|
||||||
|
ToolCalls: []llm.ToolCall{
|
||||||
|
{ID: "R1", Name: "read_document", Input: []byte(`{}`)},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Role: "user",
|
||||||
|
ToolCallID: "R1",
|
||||||
|
Content: "here are the pages",
|
||||||
|
Images: []llm.ImageContent{
|
||||||
|
{MimeType: "image/png", Data: pngBytes},
|
||||||
|
{MimeType: "application/pdf", Data: pdfBytes},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
got := buildAnthropicMessages(in, false)
|
||||||
|
require.Len(t, got, 2)
|
||||||
|
toolResult := got[1].Content[0].OfToolResult
|
||||||
|
require.NotNil(t, toolResult)
|
||||||
|
require.Len(t, toolResult.Content, 3, "image + document + text caption")
|
||||||
|
|
||||||
|
require.NotNil(t, toolResult.Content[0].OfImage)
|
||||||
|
assert.Equal(t, base64.StdEncoding.EncodeToString(pngBytes), toolResult.Content[0].OfImage.Source.OfBase64.Data)
|
||||||
|
|
||||||
|
doc := toolResult.Content[1].OfDocument
|
||||||
|
require.NotNil(t, doc, "expected a document block for the PDF attachment")
|
||||||
|
require.NotNil(t, doc.Source.OfBase64)
|
||||||
|
assert.Equal(t, base64.StdEncoding.EncodeToString(pdfBytes), doc.Source.OfBase64.Data)
|
||||||
|
|
||||||
|
require.NotNil(t, toolResult.Content[2].OfText)
|
||||||
|
assert.Equal(t, "here are the pages", toolResult.Content[2].OfText.Text)
|
||||||
|
|
||||||
|
// Confirm the wire format: media_type defaults to "application/pdf" only
|
||||||
|
// on marshal (it's a zero-value constant type until then).
|
||||||
|
raw, err := json.Marshal(toolResult.Content[1])
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Contains(t, string(raw), `"media_type":"application/pdf"`)
|
||||||
|
assert.Contains(t, string(raw), `"type":"document"`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAnthropic_UserMessageWithPDFAttachment verifies that a PDF attachment
|
||||||
|
// on a plain user message (not a tool result) also produces a document
|
||||||
|
// block rather than an image block.
|
||||||
|
func TestAnthropic_UserMessageWithPDFAttachment(t *testing.T) {
|
||||||
|
pdfBytes := []byte("%PDF-1.4 fake pdf bytes")
|
||||||
|
in := []llm.Message{
|
||||||
|
{
|
||||||
|
Role: "user",
|
||||||
|
Content: "read this",
|
||||||
|
Images: []llm.ImageContent{
|
||||||
|
{MimeType: "application/pdf", Data: pdfBytes},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
got := buildAnthropicMessages(in, false)
|
||||||
|
require.Len(t, got, 1)
|
||||||
|
require.Len(t, got[0].Content, 2, "document block + text")
|
||||||
|
doc := got[0].Content[0].OfDocument
|
||||||
|
require.NotNil(t, doc, "expected a document block for the PDF attachment")
|
||||||
|
require.NotNil(t, doc.Source.OfBase64)
|
||||||
|
assert.Equal(t, base64.StdEncoding.EncodeToString(pdfBytes), doc.Source.OfBase64.Data)
|
||||||
|
require.Nil(t, got[0].Content[0].OfImage)
|
||||||
|
require.NotNil(t, got[0].Content[1].OfText)
|
||||||
|
assert.Equal(t, "read this", got[0].Content[1].OfText.Text)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAnthropic_ImageOnlyToolResultUnchanged pins the pre-PDF behavior: a
|
||||||
|
// tool result with only image attachments (no PDFs) is unaffected by the
|
||||||
|
// PDF branch added to buildToolResultBlock.
|
||||||
|
func TestAnthropic_ImageOnlyToolResultUnchanged(t *testing.T) {
|
||||||
|
pngBytes := []byte{0x89, 0x50, 0x4E, 0x47}
|
||||||
|
in := []llm.Message{
|
||||||
|
{Role: "assistant", ToolCalls: []llm.ToolCall{{ID: "I1", Name: "snap", Input: []byte(`{}`)}}},
|
||||||
|
{Role: "user", ToolCallID: "I1", Images: []llm.ImageContent{{MimeType: "image/png", Data: pngBytes}}},
|
||||||
|
}
|
||||||
|
got := buildAnthropicMessages(in, false)
|
||||||
|
require.Len(t, got, 2)
|
||||||
|
tr := got[1].Content[0].OfToolResult
|
||||||
|
require.NotNil(t, tr)
|
||||||
|
require.Len(t, tr.Content, 1)
|
||||||
|
require.NotNil(t, tr.Content[0].OfImage)
|
||||||
|
require.Nil(t, tr.Content[0].OfDocument)
|
||||||
|
}
|
||||||
|
|
||||||
func TestAnthropicSystemPromptPartsEmitCacheControl(t *testing.T) {
|
func TestAnthropicSystemPromptPartsEmitCacheControl(t *testing.T) {
|
||||||
got := buildAnthropicSystem(llm.ChatRequest{
|
got := buildAnthropicSystem(llm.ChatRequest{
|
||||||
SystemPromptParts: []llm.SystemPromptPart{
|
SystemPromptParts: []llm.SystemPromptPart{
|
||||||
@@ -759,6 +854,27 @@ func TestOpus5AndSonnet5_ThinkByDefault_ReasoningOffSendsDisabled(t *testing.T)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestOpus5_5_ReasoningOffSendsAdaptiveLow guards against a 400 from Opus
|
||||||
|
// 5.5: its ID matches the "claude-opus-5" marker, so it inherited Opus 5's
|
||||||
|
// explicit {type:"disabled"} — which Opus 5.5 rejects ("thinking.type.disabled
|
||||||
|
// is not supported for this model"). The nearest accepted equivalent of
|
||||||
|
// "reasoning off" is adaptive thinking at low effort.
|
||||||
|
func TestOpus5_5_ReasoningOffSendsAdaptiveLow(t *testing.T) {
|
||||||
|
p := NewAnthropicProvider("test-key", "")
|
||||||
|
for _, model := range []string{"claude-opus-5-5", "claude-opus-5-5-global"} {
|
||||||
|
t.Run(model, func(t *testing.T) {
|
||||||
|
got := wireJSON(t, p, llm.ChatRequest{
|
||||||
|
Model: model,
|
||||||
|
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||||
|
})
|
||||||
|
assert.NotContains(t, got, `"disabled"`,
|
||||||
|
"Opus 5.5 rejects thinking.type.disabled")
|
||||||
|
assert.Contains(t, got, `"thinking":{"type":"adaptive"}`)
|
||||||
|
assert.Contains(t, got, `"effort":"low"`)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestLegacyThinkingModels_KeepBudgetTokens(t *testing.T) {
|
func TestLegacyThinkingModels_KeepBudgetTokens(t *testing.T) {
|
||||||
p := NewAnthropicProvider("test-key", "")
|
p := NewAnthropicProvider("test-key", "")
|
||||||
got := wireJSON(t, p, llm.ChatRequest{
|
got := wireJSON(t, p, llm.ChatRequest{
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package openai
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"github.com/sausheong/harness/llm"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPreservesOutputLimitAndTrailingUsage(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "text/event-stream")
|
||||||
|
fmt.Fprint(w, `data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"partial","type":"function","function":{"name":"bash","arguments":"{\"command\":"}}]},"finish_reason":"length"}]}`+"\n\n")
|
||||||
|
fmt.Fprint(w, `data: {"choices":[],"usage":{"prompt_tokens":50,"completion_tokens":2048,"total_tokens":2098}}`+"\n\ndata: [DONE]\n\n")
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
p := NewOpenAIProviderWithKind("fixture", srv.URL, "openai-compatible")
|
||||||
|
events, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "fixture"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for e := range events {
|
||||||
|
if e.Type == llm.EventToolCallDone {
|
||||||
|
t.Fatal("truncated tool accepted")
|
||||||
|
}
|
||||||
|
if e.Type == llm.EventError {
|
||||||
|
t.Fatal(e.Error)
|
||||||
|
}
|
||||||
|
if e.Type == llm.EventDone {
|
||||||
|
found = true
|
||||||
|
if e.StopReason != "length" || e.Usage == nil || e.Usage.OutputTokens != 2048 {
|
||||||
|
t.Fatalf("%+v", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatal("missing terminal event")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,13 @@ import (
|
|||||||
"github.com/sausheong/harness/llm"
|
"github.com/sausheong/harness/llm"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// pdfAttachmentPlaceholder replaces a PDF attachment (llm.ImageContent with
|
||||||
|
// MimeType "application/pdf") in outgoing messages: OpenAI's image_url part
|
||||||
|
// only accepts image MIME types, so sending a PDF that way would either be
|
||||||
|
// silently ignored or rejected by the API. Gemini accepts application/pdf
|
||||||
|
// inline natively and is not routed through this builder.
|
||||||
|
const pdfAttachmentPlaceholder = "[PDF attachment omitted: this provider can't read PDFs]"
|
||||||
|
|
||||||
// logOpenAIError unwraps the go-openai SDK error into a structured slog.WARN
|
// logOpenAIError unwraps the go-openai SDK error into a structured slog.WARN
|
||||||
// record so we can see exactly why LiteLLM/OpenAI rejected the request — the
|
// record so we can see exactly why LiteLLM/OpenAI rejected the request — the
|
||||||
// SDK's flat error string drops Param, Type, Code, and the raw response body
|
// SDK's flat error string drops Param, Type, Code, and the raw response body
|
||||||
@@ -129,6 +136,13 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
|||||||
if len(m.Images) > 0 {
|
if len(m.Images) > 0 {
|
||||||
var parts []openai.ChatMessagePart
|
var parts []openai.ChatMessagePart
|
||||||
for _, img := range m.Images {
|
for _, img := range m.Images {
|
||||||
|
if img.MimeType == "application/pdf" {
|
||||||
|
parts = append(parts, openai.ChatMessagePart{
|
||||||
|
Type: openai.ChatMessagePartTypeText,
|
||||||
|
Text: pdfAttachmentPlaceholder,
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
encoded := base64.StdEncoding.EncodeToString(img.Data)
|
encoded := base64.StdEncoding.EncodeToString(img.Data)
|
||||||
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
|
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
|
||||||
parts = append(parts, openai.ChatMessagePart{
|
parts = append(parts, openai.ChatMessagePart{
|
||||||
@@ -151,6 +165,13 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
|||||||
} else if len(m.Images) > 0 {
|
} else if len(m.Images) > 0 {
|
||||||
var parts []openai.ChatMessagePart
|
var parts []openai.ChatMessagePart
|
||||||
for _, img := range m.Images {
|
for _, img := range m.Images {
|
||||||
|
if img.MimeType == "application/pdf" {
|
||||||
|
parts = append(parts, openai.ChatMessagePart{
|
||||||
|
Type: openai.ChatMessagePartTypeText,
|
||||||
|
Text: pdfAttachmentPlaceholder,
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
encoded := base64.StdEncoding.EncodeToString(img.Data)
|
encoded := base64.StdEncoding.EncodeToString(img.Data)
|
||||||
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
|
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
|
||||||
parts = append(parts, openai.ChatMessagePart{
|
parts = append(parts, openai.ChatMessagePart{
|
||||||
@@ -274,6 +295,7 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
|||||||
toolCalls := make(map[int]*pendingTC)
|
toolCalls := make(map[int]*pendingTC)
|
||||||
|
|
||||||
var lastUsage *llm.Usage
|
var lastUsage *llm.Usage
|
||||||
|
var finishReason string
|
||||||
|
|
||||||
for {
|
for {
|
||||||
resp, err := stream.Recv()
|
resp, err := stream.Recv()
|
||||||
@@ -337,6 +359,9 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Finish reason
|
// Finish reason
|
||||||
|
if choice.FinishReason != "" {
|
||||||
|
finishReason = string(choice.FinishReason)
|
||||||
|
}
|
||||||
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
|
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
|
||||||
emitToolCalls(events, toolCalls)
|
emitToolCalls(events, toolCalls)
|
||||||
clear(toolCalls)
|
clear(toolCalls)
|
||||||
@@ -344,7 +369,7 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
|
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage, StopReason: finishReason}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return events, nil
|
return events, nil
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
openai "github.com/sashabaranov/go-openai"
|
openai "github.com/sashabaranov/go-openai"
|
||||||
@@ -74,6 +75,75 @@ func TestOpenAIChatStreamPartsBeatString(t *testing.T) {
|
|||||||
require.Equal(t, "new", captured.Messages[0].Content)
|
require.Equal(t, "new", captured.Messages[0].Content)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestOpenAIChatStream_PDFToolResultOmittedWithPlaceholder verifies that a
|
||||||
|
// PDF attachment on a tool result is never emitted as an image_url data
|
||||||
|
// URI (which would be invalid — image_url expects an image MIME type) and
|
||||||
|
// that the placeholder text takes its place; a real image attachment in
|
||||||
|
// the same result is still emitted.
|
||||||
|
func TestOpenAIChatStream_PDFToolResultOmittedWithPlaceholder(t *testing.T) {
|
||||||
|
pngBytes := []byte{0x89, 0x50, 0x4E, 0x47}
|
||||||
|
pdfBytes := []byte("%PDF-1.4 fake")
|
||||||
|
captured := captureOpenAIRequest(t, llm.ChatRequest{
|
||||||
|
Messages: []llm.Message{
|
||||||
|
{
|
||||||
|
Role: "user",
|
||||||
|
ToolCallID: "T1",
|
||||||
|
Content: "see attached",
|
||||||
|
Images: []llm.ImageContent{
|
||||||
|
{MimeType: "image/png", Data: pngBytes},
|
||||||
|
{MimeType: "application/pdf", Data: pdfBytes},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
require.NotNil(t, captured)
|
||||||
|
|
||||||
|
var sawImage, sawPlaceholder bool
|
||||||
|
for _, m := range captured.Messages {
|
||||||
|
for _, part := range m.MultiContent {
|
||||||
|
if part.Type == openai.ChatMessagePartTypeImageURL && part.ImageURL != nil {
|
||||||
|
require.NotContains(t, part.ImageURL.URL, "application/pdf", "a PDF must never be sent as image_url")
|
||||||
|
sawImage = true
|
||||||
|
}
|
||||||
|
if part.Type == openai.ChatMessagePartTypeText && strings.Contains(part.Text, pdfAttachmentPlaceholder) {
|
||||||
|
sawPlaceholder = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require.True(t, sawImage, "the PNG attachment must still be emitted as image_url")
|
||||||
|
require.True(t, sawPlaceholder, "the PDF attachment must be replaced with the placeholder text")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOpenAIChatStream_PDFUserMessageOmittedWithPlaceholder covers the
|
||||||
|
// plain user-message image branch (not a tool result).
|
||||||
|
func TestOpenAIChatStream_PDFUserMessageOmittedWithPlaceholder(t *testing.T) {
|
||||||
|
pdfBytes := []byte("%PDF-1.4 fake")
|
||||||
|
captured := captureOpenAIRequest(t, llm.ChatRequest{
|
||||||
|
Messages: []llm.Message{
|
||||||
|
{
|
||||||
|
Role: "user",
|
||||||
|
Content: "read this",
|
||||||
|
Images: []llm.ImageContent{{MimeType: "application/pdf", Data: pdfBytes}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
require.NotNil(t, captured)
|
||||||
|
|
||||||
|
var sawImageURL, sawPlaceholder bool
|
||||||
|
for _, m := range captured.Messages {
|
||||||
|
for _, part := range m.MultiContent {
|
||||||
|
if part.Type == openai.ChatMessagePartTypeImageURL {
|
||||||
|
sawImageURL = true
|
||||||
|
}
|
||||||
|
if part.Type == openai.ChatMessagePartTypeText && strings.Contains(part.Text, pdfAttachmentPlaceholder) {
|
||||||
|
sawPlaceholder = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require.False(t, sawImageURL, "a PDF must never be sent as image_url")
|
||||||
|
require.True(t, sawPlaceholder, "the PDF attachment must be replaced with the placeholder text")
|
||||||
|
}
|
||||||
|
|
||||||
func TestEmitToolCalls_OrderedByIndex(t *testing.T) {
|
func TestEmitToolCalls_OrderedByIndex(t *testing.T) {
|
||||||
mk := func(id, name string) *pendingTC {
|
mk := func(id, name string) *pendingTC {
|
||||||
p := &pendingTC{id: id, name: name}
|
p := &pendingTC{id: id, name: name}
|
||||||
|
|||||||
@@ -24,7 +24,8 @@ func (p *attachmentReplayProvider) ChatStream(_ context.Context, req llm.ChatReq
|
|||||||
for _, msg := range req.Messages {
|
for _, msg := range req.Messages {
|
||||||
p.images = append(p.images, msg.Images...)
|
p.images = append(p.images, msg.Images...)
|
||||||
}
|
}
|
||||||
events := make(chan llm.ChatEvent, 1)
|
events := make(chan llm.ChatEvent, 2)
|
||||||
|
events <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
|
||||||
events <- llm.ChatEvent{Type: llm.EventDone}
|
events <- llm.ChatEvent{Type: llm.EventDone}
|
||||||
close(events)
|
close(events)
|
||||||
return events, nil
|
return events, nil
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package runtime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/sausheong/harness/llm"
|
||||||
|
"github.com/sausheong/harness/llm/llmtest"
|
||||||
|
"github.com/sausheong/harness/session"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type emptyResponseProvider struct {
|
||||||
|
llmtest.Base
|
||||||
|
responses [][]llm.ChatEvent
|
||||||
|
calls int
|
||||||
|
limits []int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *emptyResponseProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||||
|
p.limits = append(p.limits, req.MaxTokens)
|
||||||
|
i := min(p.calls, len(p.responses)-1)
|
||||||
|
p.calls++
|
||||||
|
ch := make(chan llm.ChatEvent, len(p.responses[i]))
|
||||||
|
for _, e := range p.responses[i] {
|
||||||
|
ch <- e
|
||||||
|
}
|
||||||
|
close(ch)
|
||||||
|
return ch, nil
|
||||||
|
}
|
||||||
|
func TestEmptyAndTruncatedResponses(t *testing.T) {
|
||||||
|
done := llm.ChatEvent{Type: llm.EventDone, StopReason: "stop"}
|
||||||
|
text := llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
responses [][]llm.ChatEvent
|
||||||
|
calls int
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"empty", [][]llm.ChatEvent{{done}}, 2, "no answer"},
|
||||||
|
{"recovery", [][]llm.ChatEvent{{done}, {text, done}}, 2, ""},
|
||||||
|
{"normal", [][]llm.ChatEvent{{text, done}}, 1, ""},
|
||||||
|
{"length", [][]llm.ChatEvent{{{Type: llm.EventDone, StopReason: "length", Usage: &llm.Usage{OutputTokens: 2048}}}}, 1, "output limit"},
|
||||||
|
{"partial", [][]llm.ChatEvent{{text, {Type: llm.EventDone, StopReason: "max_tokens"}}}, 1, "output limit"},
|
||||||
|
{"whitespace", [][]llm.ChatEvent{{{Type: llm.EventTextDelta, Text: " \n"}, done}}, 1, "no answer"},
|
||||||
|
{"thinking", [][]llm.ChatEvent{{{Type: llm.EventThinkingBlock, ThinkingBlock: &llm.ThinkingBlock{Thinking: "opaque"}}, done}}, 2, "no answer"},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
p := &emptyResponseProvider{responses: tc.responses}
|
||||||
|
rt := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("test", "test"), Model: "fixture", MaxOutputTokens: 2048, MaxTurns: 2}
|
||||||
|
reason := ""
|
||||||
|
rt.AgentLoop.Hooks.OnStop = func(_ context.Context, r string) { reason = r }
|
||||||
|
events, err := rt.Run(context.Background(), "question", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var failure error
|
||||||
|
for e := range events {
|
||||||
|
if e.Type == EventError {
|
||||||
|
failure = e.Error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if tc.want == "" {
|
||||||
|
if failure != nil || reason != "completed" {
|
||||||
|
t.Fatalf("%v %s", failure, reason)
|
||||||
|
}
|
||||||
|
} else if failure == nil || !strings.Contains(failure.Error(), tc.want) || reason == "completed" {
|
||||||
|
t.Fatalf("%v %s", failure, reason)
|
||||||
|
}
|
||||||
|
if p.calls != tc.calls {
|
||||||
|
t.Fatalf("calls %d", p.calls)
|
||||||
|
}
|
||||||
|
for _, limit := range p.limits {
|
||||||
|
if limit != 2048 {
|
||||||
|
t.Fatalf("changed limit %d", limit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSingleTurnRejectsEmptyAndTruncatedResponses(t *testing.T) {
|
||||||
|
for _, reason := range []string{"stop", "length", "max_tokens"} {
|
||||||
|
t.Run(reason, func(t *testing.T) {
|
||||||
|
p := &emptyResponseProvider{responses: [][]llm.ChatEvent{{{Type: llm.EventDone, StopReason: reason}}}}
|
||||||
|
rt := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("test", "single"), Model: "fixture", MaxOutputTokens: 2048}
|
||||||
|
result, err := rt.RunTurn(context.Background(), "question", nil, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Err == nil || result.StopReason == "completed" || p.calls != 1 {
|
||||||
|
t.Fatalf("%+v calls=%d", result, p.calls)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,7 +20,8 @@ func (p *outputLimitProvider) ChatStream(_ context.Context, r llm.ChatRequest) (
|
|||||||
if p.fallback && len(p.limits) == 1 {
|
if p.fallback && len(p.limits) == 1 {
|
||||||
return nil, errors.New("529 overloaded")
|
return nil, errors.New("529 overloaded")
|
||||||
}
|
}
|
||||||
ch := make(chan llm.ChatEvent, 1)
|
ch := make(chan llm.ChatEvent, 2)
|
||||||
|
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
|
||||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||||
close(ch)
|
close(ch)
|
||||||
return ch, nil
|
return ch, nil
|
||||||
|
|||||||
@@ -0,0 +1,168 @@
|
|||||||
|
package runtime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/sausheong/harness/llm"
|
||||||
|
"github.com/sausheong/harness/llm/llmtest"
|
||||||
|
"github.com/sausheong/harness/session"
|
||||||
|
"github.com/sausheong/harness/tool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestConvertToolResultImages_PreservesPDFMimeType pins convertToolResultImages'
|
||||||
|
// behavior for a PDF attachment: the MimeType is carried through unchanged
|
||||||
|
// (it is not an image format convertToolResultImages inspects or rewrites).
|
||||||
|
func TestConvertToolResultImages_PreservesPDFMimeType(t *testing.T) {
|
||||||
|
pdfBytes := []byte("%PDF-1.4 fake")
|
||||||
|
out := convertToolResultImages([]llm.ImageContent{{MimeType: "application/pdf", Data: pdfBytes}})
|
||||||
|
if len(out) != 1 {
|
||||||
|
t.Fatalf("len(out) = %d, want 1", len(out))
|
||||||
|
}
|
||||||
|
if out[0].MimeType != "application/pdf" {
|
||||||
|
t.Fatalf("MimeType = %q, want application/pdf", out[0].MimeType)
|
||||||
|
}
|
||||||
|
decoded, err := base64.StdEncoding.DecodeString(out[0].Data)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("decode: %v", err)
|
||||||
|
}
|
||||||
|
if string(decoded) != string(pdfBytes) {
|
||||||
|
t.Fatalf("Data = %q, want %q", decoded, pdfBytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSessionRoundTrip_ToolResultPDFAttachment writes a
|
||||||
|
// ToolResultWithArtifactsEntry carrying a PDF attachment through
|
||||||
|
// session.ToolResultWithArtifactsEntry, round-trips it through JSON exactly
|
||||||
|
// as disk storage does, and confirms decoding it back reproduces the
|
||||||
|
// MimeType and bytes untouched.
|
||||||
|
func TestSessionRoundTrip_ToolResultPDFAttachment(t *testing.T) {
|
||||||
|
pdfBytes := []byte("%PDF-1.4 fake pdf")
|
||||||
|
images := []session.ImageData{{MimeType: "application/pdf", Data: base64.StdEncoding.EncodeToString(pdfBytes)}}
|
||||||
|
entry := session.ToolResultWithArtifactsEntry("tc_1", "showing pages", "", images, nil)
|
||||||
|
|
||||||
|
raw, err := json.Marshal(entry)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal: %v", err)
|
||||||
|
}
|
||||||
|
var decoded session.SessionEntry
|
||||||
|
if err := json.Unmarshal(raw, &decoded); err != nil {
|
||||||
|
t.Fatalf("unmarshal: %v", err)
|
||||||
|
}
|
||||||
|
var tr session.ToolResultData
|
||||||
|
if err := json.Unmarshal(decoded.Data, &tr); err != nil {
|
||||||
|
t.Fatalf("unmarshal tool result data: %v", err)
|
||||||
|
}
|
||||||
|
if len(tr.Images) != 1 || tr.Images[0].MimeType != "application/pdf" {
|
||||||
|
t.Fatalf("tr.Images = %+v, want one application/pdf image", tr.Images)
|
||||||
|
}
|
||||||
|
gotBytes, err := base64.StdEncoding.DecodeString(tr.Images[0].Data)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("decode: %v", err)
|
||||||
|
}
|
||||||
|
if string(gotBytes) != string(pdfBytes) {
|
||||||
|
t.Fatalf("Data = %q, want %q", gotBytes, pdfBytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// pdfToolResultProvider issues one tool call on its first turn, then on the
|
||||||
|
// second turn records the images (and their MimeTypes) it received in the
|
||||||
|
// tool_result message.
|
||||||
|
type pdfToolResultProvider struct {
|
||||||
|
llmtest.Base
|
||||||
|
calls int
|
||||||
|
images []llm.ImageContent
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pdfToolResultProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||||
|
p.calls++
|
||||||
|
events := make(chan llm.ChatEvent, 4)
|
||||||
|
if p.calls == 1 {
|
||||||
|
events <- llm.ChatEvent{Type: llm.EventToolCallStart, ToolCall: &llm.ToolCall{ID: "tc_1", Name: "read_document"}}
|
||||||
|
events <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "tc_1", Name: "read_document", Input: json.RawMessage(`{}`)}}
|
||||||
|
events <- llm.ChatEvent{Type: llm.EventDone, StopReason: "tool_use"}
|
||||||
|
close(events)
|
||||||
|
return events, nil
|
||||||
|
}
|
||||||
|
for _, msg := range req.Messages {
|
||||||
|
p.images = append(p.images, msg.Images...)
|
||||||
|
}
|
||||||
|
events <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "done"}
|
||||||
|
events <- llm.ChatEvent{Type: llm.EventDone}
|
||||||
|
close(events)
|
||||||
|
return events, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// pdfExecutor is a minimal tool.Executor whose one tool ("read_document")
|
||||||
|
// always returns a PDF attachment, standing in for readdoc_tool.go's real
|
||||||
|
// behavior for this harness-side round-trip test.
|
||||||
|
type pdfExecutor struct{ pdfBytes []byte }
|
||||||
|
|
||||||
|
func newPDFTestRegistry(pdfBytes []byte) tool.Executor { return pdfExecutor{pdfBytes: pdfBytes} }
|
||||||
|
|
||||||
|
func (e pdfExecutor) Execute(_ context.Context, name string, _ json.RawMessage) (tool.ToolResult, error) {
|
||||||
|
if name != "read_document" {
|
||||||
|
return tool.ToolResult{Error: "unknown tool"}, nil
|
||||||
|
}
|
||||||
|
return tool.ToolResult{
|
||||||
|
Output: "showing pages",
|
||||||
|
Images: []llm.ImageContent{{MimeType: "application/pdf", Data: e.pdfBytes}},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
func (e pdfExecutor) ToolDefs() []llm.ToolDef { return []llm.ToolDef{{Name: "read_document"}} }
|
||||||
|
func (e pdfExecutor) Names() []string { return []string{"read_document"} }
|
||||||
|
func (e pdfExecutor) Get(string) (tool.Tool, bool) { return nil, false }
|
||||||
|
|
||||||
|
// TestRuntimePDFAttachmentSurvivesSessionAppendAndReachesNextTurn drives a
|
||||||
|
// full tool-call round trip: a tool returns a PDF attachment, the runtime
|
||||||
|
// appends it to the session as a ToolResultWithArtifactsEntry, and the very
|
||||||
|
// next LLM request (assembled from that same session) must carry the PDF
|
||||||
|
// back with MimeType "application/pdf" intact.
|
||||||
|
func TestRuntimePDFAttachmentSurvivesSessionAppendAndReachesNextTurn(t *testing.T) {
|
||||||
|
pdfBytes := []byte("%PDF-1.4 fake pdf pages")
|
||||||
|
sess := session.NewSession("agent", "key")
|
||||||
|
provider := &pdfToolResultProvider{}
|
||||||
|
reg := newPDFTestRegistry(pdfBytes)
|
||||||
|
|
||||||
|
rt := &Runtime{Session: sess, LLM: provider, Tools: reg, Model: "model", MaxTurns: 3}
|
||||||
|
if _, err := rt.RunSync(context.Background(), "read this pdf", nil); err != nil {
|
||||||
|
t.Fatalf("RunSync() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if provider.calls != 2 {
|
||||||
|
t.Fatalf("provider.calls = %d, want 2", provider.calls)
|
||||||
|
}
|
||||||
|
if len(provider.images) != 1 {
|
||||||
|
t.Fatalf("len(provider.images) = %d, want 1", len(provider.images))
|
||||||
|
}
|
||||||
|
if provider.images[0].MimeType != "application/pdf" {
|
||||||
|
t.Fatalf("MimeType = %q, want application/pdf", provider.images[0].MimeType)
|
||||||
|
}
|
||||||
|
if string(provider.images[0].Data) != string(pdfBytes) {
|
||||||
|
t.Fatalf("Data mismatch: got %d bytes, want %d bytes", len(provider.images[0].Data), len(pdfBytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Confirm the session entry itself carries the PDF MimeType, not just
|
||||||
|
// the reconstructed message — i.e. the append path (not only assembly)
|
||||||
|
// preserved it.
|
||||||
|
var found bool
|
||||||
|
for _, e := range sess.History() {
|
||||||
|
if e.Type != session.EntryTypeToolResult {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var tr session.ToolResultData
|
||||||
|
if err := json.Unmarshal(e.Data, &tr); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, img := range tr.Images {
|
||||||
|
if img.MimeType == "application/pdf" {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatal("no application/pdf image found in session history's tool_result entry")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,6 +29,9 @@ func (p *requestUsageProvider) ChatStream(_ context.Context, req llm.ChatRequest
|
|||||||
if p.calls < p.total {
|
if p.calls < p.total {
|
||||||
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: req.Model, Name: "noop", Input: json.RawMessage(`{}`)}}
|
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: req.Model, Name: "noop", Input: json.RawMessage(`{}`)}}
|
||||||
}
|
}
|
||||||
|
if p.calls >= p.total {
|
||||||
|
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
|
||||||
|
}
|
||||||
usage := &llm.Usage{InputTokens: 20000, OutputTokens: 100, CacheReadInputTokens: 15000}
|
usage := &llm.Usage{InputTokens: 20000, OutputTokens: 100, CacheReadInputTokens: 15000}
|
||||||
if p.missingLast && p.calls == p.total {
|
if p.missingLast && p.calls == p.total {
|
||||||
usage = nil
|
usage = nil
|
||||||
@@ -87,7 +90,10 @@ type refusalUsageProvider struct {
|
|||||||
|
|
||||||
func (p *refusalUsageProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
func (p *refusalUsageProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||||
p.calls++
|
p.calls++
|
||||||
ch := make(chan llm.ChatEvent, 1)
|
ch := make(chan llm.ChatEvent, 2)
|
||||||
|
if p.calls > 1 {
|
||||||
|
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
|
||||||
|
}
|
||||||
e := llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 10000}}
|
e := llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 10000}}
|
||||||
if p.calls == 1 {
|
if p.calls == 1 {
|
||||||
e.StopReason = llm.StopReasonRefusal
|
e.StopReason = llm.StopReasonRefusal
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ func TestRunLifecycleStartFailureAndFinishCannotChangeOutcome(t *testing.T) {
|
|||||||
t.Error("finish unbounded")
|
t.Error("finish unbounded")
|
||||||
}
|
}
|
||||||
panic("observer cannot rewrite outcome")
|
panic("observer cannot rewrite outcome")
|
||||||
}}, []llm.ChatEvent{{Type: llm.EventDone}}, nil)
|
}}, []llm.ChatEvent{{Type: llm.EventTextDelta, Text: "Answer"}, {Type: llm.EventDone}}, nil)
|
||||||
defer rt.Close()
|
defer rt.Close()
|
||||||
defer rt.Session.Close()
|
defer rt.Session.Close()
|
||||||
failed := false
|
failed := false
|
||||||
|
|||||||
@@ -34,6 +34,8 @@ const (
|
|||||||
EventCompactionDone
|
EventCompactionDone
|
||||||
EventCompactionSkipped
|
EventCompactionSkipped
|
||||||
EventRequestUsage
|
EventRequestUsage
|
||||||
|
// EventToolCallReady carries complete arguments before tool execution.
|
||||||
|
EventToolCallReady
|
||||||
)
|
)
|
||||||
|
|
||||||
// AgentEvent is a single streaming event from the agent.
|
// AgentEvent is a single streaming event from the agent.
|
||||||
@@ -687,6 +689,8 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
|||||||
preTokenRetried := false
|
preTokenRetried := false
|
||||||
retriedRefusal := false
|
retriedRefusal := false
|
||||||
var refused bool
|
var refused bool
|
||||||
|
retriedEmpty := false
|
||||||
|
var terminalReason string
|
||||||
var refusalCategory string
|
var refusalCategory string
|
||||||
streamLoop:
|
streamLoop:
|
||||||
for {
|
for {
|
||||||
@@ -728,6 +732,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
|||||||
}
|
}
|
||||||
break streamLoop
|
break streamLoop
|
||||||
}
|
}
|
||||||
|
r.emit(AgentEvent{Type: EventToolCallReady, ToolCall: &tc})
|
||||||
toolCalls = append(toolCalls, tc)
|
toolCalls = append(toolCalls, tc)
|
||||||
if !streamingOn || kickoffStopped {
|
if !streamingOn || kickoffStopped {
|
||||||
continue
|
continue
|
||||||
@@ -746,6 +751,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
case llm.EventDone:
|
case llm.EventDone:
|
||||||
|
terminalReason = event.StopReason
|
||||||
refused = event.StopReason == llm.StopReasonRefusal
|
refused = event.StopReason == llm.StopReasonRefusal
|
||||||
refusalCategory = event.StopCategory
|
refusalCategory = event.StopCategory
|
||||||
if event.Usage != nil && r.calibrator != nil {
|
if event.Usage != nil && r.calibrator != nil {
|
||||||
@@ -871,6 +877,22 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
|||||||
textContent.WriteString(note)
|
textContent.WriteString(note)
|
||||||
r.emit(AgentEvent{Type: EventTextDelta, Text: note})
|
r.emit(AgentEvent{Type: EventTextDelta, Text: note})
|
||||||
}
|
}
|
||||||
|
// Retry only an empty, non-truncated response with no tool activity.
|
||||||
|
// Keep the same request and output allowance; never replay tools.
|
||||||
|
limited := terminalReason == "length" || terminalReason == "max_tokens"
|
||||||
|
if !limited && !refused && strings.TrimSpace(textContent.String()) == "" && len(toolCalls) == 0 && len(kickoffs) == 0 && !gotFirstToken && !retriedEmpty {
|
||||||
|
retriedEmpty = true
|
||||||
|
terminalReason = ""
|
||||||
|
thinkingBlocks = nil
|
||||||
|
retryStream, retryErr := r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
|
||||||
|
if retryErr != nil {
|
||||||
|
stopReason = "error"
|
||||||
|
r.emit(AgentEvent{Type: EventError, Error: retryErr})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
streamSource = retryStream
|
||||||
|
continue streamLoop
|
||||||
|
}
|
||||||
break streamLoop
|
break streamLoop
|
||||||
}
|
}
|
||||||
tr.Mark("llm.stream_end", "turn", turn,
|
tr.Mark("llm.stream_end", "turn", turn,
|
||||||
@@ -909,6 +931,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if len(toolCalls) == 0 {
|
if len(toolCalls) == 0 {
|
||||||
|
var responseErr error
|
||||||
|
if terminalReason == "length" || terminalReason == "max_tokens" {
|
||||||
|
responseErr = fmt.Errorf("model reached its output limit (%d tokens) before finishing; increase max_output or use a model with a larger output allowance", req.MaxTokens)
|
||||||
|
} else if strings.TrimSpace(textContent.String()) == "" {
|
||||||
|
responseErr = errors.New("model returned no answer; try again or choose another model")
|
||||||
|
}
|
||||||
|
if responseErr != nil {
|
||||||
|
drainKickoffs(kickoffs)
|
||||||
|
stopReason = "error"
|
||||||
|
r.emit(AgentEvent{Type: EventError, Error: responseErr})
|
||||||
|
return
|
||||||
|
}
|
||||||
if len(kickoffs) > 0 {
|
if len(kickoffs) > 0 {
|
||||||
drainKickoffs(kickoffs)
|
drainKickoffs(kickoffs)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -173,6 +173,7 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
|
|||||||
var toolCalls []llm.ToolCall
|
var toolCalls []llm.ToolCall
|
||||||
var thinkingBlocks []session.ThinkingBlockData
|
var thinkingBlocks []session.ThinkingBlockData
|
||||||
retriedRefusal := false
|
retriedRefusal := false
|
||||||
|
var terminalReason string
|
||||||
streamLoop:
|
streamLoop:
|
||||||
for {
|
for {
|
||||||
toolIDs := make(map[string]bool)
|
toolIDs := make(map[string]bool)
|
||||||
@@ -205,9 +206,11 @@ streamLoop:
|
|||||||
emit(AgentEvent{Type: EventError, Error: err})
|
emit(AgentEvent{Type: EventError, Error: err})
|
||||||
return r.turnSlice(startLen, true, "error", ledger.Total(), err), nil
|
return r.turnSlice(startLen, true, "error", ledger.Total(), err), nil
|
||||||
}
|
}
|
||||||
|
emit(AgentEvent{Type: EventToolCallReady, ToolCall: event.ToolCall})
|
||||||
toolCalls = append(toolCalls, *event.ToolCall)
|
toolCalls = append(toolCalls, *event.ToolCall)
|
||||||
}
|
}
|
||||||
case llm.EventDone:
|
case llm.EventDone:
|
||||||
|
terminalReason = event.StopReason
|
||||||
refused = event.StopReason == llm.StopReasonRefusal
|
refused = event.StopReason == llm.StopReasonRefusal
|
||||||
refusalCategory = event.StopCategory
|
refusalCategory = event.StopCategory
|
||||||
case llm.EventError:
|
case llm.EventError:
|
||||||
@@ -257,6 +260,16 @@ streamLoop:
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(toolCalls) == 0 {
|
if len(toolCalls) == 0 {
|
||||||
|
var responseErr error
|
||||||
|
if terminalReason == "length" || terminalReason == "max_tokens" {
|
||||||
|
responseErr = fmt.Errorf("model reached its output limit (%d tokens) before finishing; increase max_output or use a model with a larger output allowance", req.MaxTokens)
|
||||||
|
} else if strings.TrimSpace(textContent.String()) == "" {
|
||||||
|
responseErr = fmt.Errorf("model returned no answer; try again or choose another model")
|
||||||
|
}
|
||||||
|
if responseErr != nil {
|
||||||
|
emit(AgentEvent{Type: EventError, Error: responseErr})
|
||||||
|
return r.turnSlice(startLen, true, "error", ledger.Total(), responseErr), nil
|
||||||
|
}
|
||||||
// Exchange complete: ingest the full thread once. Background + best-effort
|
// Exchange complete: ingest the full thread once. Background + best-effort
|
||||||
// (the KG spawns its own bounded goroutine), so it never delays the turn.
|
// (the KG spawns its own bounded goroutine), so it never delays the turn.
|
||||||
// context.Background() because the request ctx may be cancelling and the
|
// context.Background() because the request ctx may be cancelling and the
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ func (p *authoringProvider) ChatStream(_ context.Context, req llm.ChatRequest) (
|
|||||||
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "author", Name: "skill_manage", Input: json.RawMessage(`{"action":"create","name":"authored-skill","body":"---\ndescription: newly authored workflow\n---\nunique procedure body"}`)}}
|
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "author", Name: "skill_manage", Input: json.RawMessage(`{"action":"create","name":"authored-skill","body":"---\ndescription: newly authored workflow\n---\nunique procedure body"}`)}}
|
||||||
case 2:
|
case 2:
|
||||||
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "load", Name: "load_skill", Input: json.RawMessage(`{"name":"authored-skill"}`)}}
|
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "load", Name: "load_skill", Input: json.RawMessage(`{"name":"authored-skill"}`)}}
|
||||||
|
default:
|
||||||
|
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Skill created and loaded."}
|
||||||
}
|
}
|
||||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||||
close(ch)
|
close(ch)
|
||||||
|
|||||||
@@ -102,7 +102,8 @@ func (s *scriptedStreamLLM) ChatStream(ctx context.Context, _ llm.ChatRequest) (
|
|||||||
go func() {
|
go func() {
|
||||||
defer close(out)
|
defer close(out)
|
||||||
if n != 1 {
|
if n != 1 {
|
||||||
// Subsequent turns: terminate quickly with no tool calls.
|
// Subsequent turns: answer without further tool calls.
|
||||||
|
out <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
|
||||||
out <- llm.ChatEvent{Type: llm.EventDone}
|
out <- llm.ChatEvent{Type: llm.EventDone}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package runtime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/sausheong/harness/llm"
|
||||||
|
"github.com/sausheong/harness/session"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestToolReadyCarriesArgumentsBeforeResult(t *testing.T) {
|
||||||
|
provider := &emptyResponseProvider{responses: [][]llm.ChatEvent{
|
||||||
|
{{Type: llm.EventToolCallStart, ToolCall: &llm.ToolCall{ID: "one", Name: "noop"}}, {Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "one", Name: "noop", Input: []byte(`{"command":"echo hi"}`)}}, {Type: llm.EventDone}},
|
||||||
|
{{Type: llm.EventTextDelta, Text: "Done"}, {Type: llm.EventDone}},
|
||||||
|
}}
|
||||||
|
rt := &Runtime{LLM: provider, Tools: usageNoopExecutor{}, Session: session.NewSession("test", "ready"), Model: "fixture", MaxTurns: 2}
|
||||||
|
stream, err := rt.Run(context.Background(), "go", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ready, results := 0, 0
|
||||||
|
for e := range stream {
|
||||||
|
switch e.Type {
|
||||||
|
case EventToolCallReady:
|
||||||
|
ready++
|
||||||
|
if e.ToolCall == nil || string(e.ToolCall.Input) != `{"command":"echo hi"}` {
|
||||||
|
t.Fatalf("%+v", e)
|
||||||
|
}
|
||||||
|
case EventToolResult:
|
||||||
|
results++
|
||||||
|
if ready != 1 {
|
||||||
|
t.Fatal("result before arguments")
|
||||||
|
}
|
||||||
|
case EventError:
|
||||||
|
t.Fatal(e.Error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ready != 1 || results != 1 {
|
||||||
|
t.Fatalf("ready=%d results=%d", ready, results)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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": "<label>" on EVERY call. Sessions auto-close after 10 minutes idle (max 5).
|
||||||
|
|
||||||
|
ACTIONS:
|
||||||
|
- "navigate": Go to "url". Returns the page title and final URL.
|
||||||
|
- "act": Perform ONE atomic action described by "instruction", e.g. "click the Sign in button", "type 'laptop' into the search box", "select 'Newest' in the sort dropdown". Break multi-step tasks into several act calls.
|
||||||
|
- "observe": List actionable elements matching "instruction" (optional, e.g. "find the pagination links"). Returns descriptions and selectors without acting.
|
||||||
|
- "extract": Extract data described by "instruction", e.g. "the title and price of every product". Optional "schema" (JSON Schema object) describes the exact shape you want. Returns JSON.
|
||||||
|
- "get_text": Return the visible text of the current page.
|
||||||
|
- "screenshot": Screenshot the current page ("full_page": true for the whole page). Returns the image.
|
||||||
|
- "close": Close a persistent session. Requires "session".
|
||||||
|
|
||||||
|
Any action except "close" accepts "url" to navigate first.
|
||||||
|
|
||||||
|
EXAMPLE:
|
||||||
|
1) {"action":"navigate","url":"https://news.ycombinator.com","session":"hn"}
|
||||||
|
2) {"action":"act","instruction":"click the 'new' link in the top bar","session":"hn"}
|
||||||
|
3) {"action":"extract","instruction":"the title and points of the first 5 stories","session":"hn"}
|
||||||
|
4) {"action":"close","session":"hn"}
|
||||||
|
|
||||||
|
Never put passwords or secrets inside "instruction" — instructions are sent to an LLM.`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *StagehandTool) Parameters() json.RawMessage {
|
||||||
|
return json.RawMessage(`{
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"action": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["navigate", "act", "observe", "extract", "get_text", "screenshot", "close"],
|
||||||
|
"description": "The browser action to perform"
|
||||||
|
},
|
||||||
|
"session": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Optional session name. The browser persists across calls with the same name. Omit for one-shot calls. Required for close."
|
||||||
|
},
|
||||||
|
"url": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "URL to navigate to (required for navigate; optional for other actions, which navigate first)"
|
||||||
|
},
|
||||||
|
"instruction": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Natural-language instruction (required for act and extract; optional for observe)"
|
||||||
|
},
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "Optional JSON Schema describing the data shape for extract"
|
||||||
|
},
|
||||||
|
"full_page": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "For screenshot: capture the full scrollable page instead of the viewport"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["action"]
|
||||||
|
}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsConcurrencySafe returns false — sessions are stateful.
|
||||||
|
func (t *StagehandTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
|
||||||
|
|
||||||
|
func (t *StagehandTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||||
|
var in stagehandInput
|
||||||
|
if err := json.Unmarshal(input, &in); err != nil {
|
||||||
|
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
|
||||||
|
}
|
||||||
|
if msg := validate(in); msg != "" {
|
||||||
|
return tool.ToolResult{Error: msg}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if in.Action == "close" {
|
||||||
|
if t.closeSession(in.Session) {
|
||||||
|
return tool.ToolResult{Output: fmt.Sprintf("Closed session %q", in.Session)}, nil
|
||||||
|
}
|
||||||
|
return tool.ToolResult{Output: fmt.Sprintf("No active session %q", in.Session)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
callCtx, cancel := context.WithTimeout(ctx, callTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
sess, release, err := t.acquire(callCtx, in.Session)
|
||||||
|
if err != nil {
|
||||||
|
return tool.ToolResult{Error: err.Error()}, nil
|
||||||
|
}
|
||||||
|
defer release()
|
||||||
|
|
||||||
|
return t.dispatch(callCtx, sess, in)
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate returns a user-facing error message, or "" when in is valid.
|
||||||
|
func validate(in stagehandInput) string {
|
||||||
|
switch in.Action {
|
||||||
|
case "":
|
||||||
|
return "action is required"
|
||||||
|
case "close":
|
||||||
|
if in.Session == "" {
|
||||||
|
return "session is required for close action"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
case "navigate":
|
||||||
|
if in.URL == "" {
|
||||||
|
return "url is required for navigate action"
|
||||||
|
}
|
||||||
|
case "act", "extract":
|
||||||
|
if strings.TrimSpace(in.Instruction) == "" {
|
||||||
|
return fmt.Sprintf("instruction is required for %s action", in.Action)
|
||||||
|
}
|
||||||
|
case "observe", "get_text", "screenshot":
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("unknown action: %q (valid: navigate, act, observe, extract, get_text, screenshot, close)", in.Action)
|
||||||
|
}
|
||||||
|
if in.URL != "" {
|
||||||
|
if !strings.HasPrefix(in.URL, "http://") && !strings.HasPrefix(in.URL, "https://") {
|
||||||
|
return "url must start with http:// or https://"
|
||||||
|
}
|
||||||
|
if err := web.ValidateURLNotInternal(in.URL); err != nil {
|
||||||
|
return fmt.Sprintf("navigate failed: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if in.URL == "" && in.Session == "" {
|
||||||
|
return fmt.Sprintf("%s called without 'url' or 'session'. Each call without a session uses a fresh browser on about:blank, so state does NOT carry over. Either pass 'url' to navigate first, or pass the same 'session' on every call in a multi-step flow.", in.Action)
|
||||||
|
}
|
||||||
|
if len(in.Schema) > 0 && in.Action == "extract" {
|
||||||
|
var probe map[string]any
|
||||||
|
if err := json.Unmarshal(in.Schema, &probe); err != nil {
|
||||||
|
return "schema must be a JSON object"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *StagehandTool) dispatch(ctx context.Context, sess *session, in stagehandInput) (tool.ToolResult, error) {
|
||||||
|
bctx, err := sess.browser.Context()
|
||||||
|
if err != nil {
|
||||||
|
return tool.ToolResult{Error: fmt.Sprintf("browser context: %v", err)}, nil
|
||||||
|
}
|
||||||
|
page, err := bctx.ActivePage(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return tool.ToolResult{Error: fmt.Sprintf("active page: %v", err)}, nil
|
||||||
|
}
|
||||||
|
if in.URL != "" {
|
||||||
|
if _, err := page.Goto(ctx, in.URL, nil); err != nil {
|
||||||
|
return tool.ToolResult{Error: fmt.Sprintf("navigate failed: %v", err)}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch in.Action {
|
||||||
|
case "navigate":
|
||||||
|
title, _ := page.Title(ctx)
|
||||||
|
url, _ := page.URL(ctx)
|
||||||
|
return tool.ToolResult{Output: fmt.Sprintf("Navigated to %s\nTitle: %s", url, title)}, nil
|
||||||
|
|
||||||
|
case "act":
|
||||||
|
res, err := sess.client.Act(ctx, sh.ActInstruction(in.Instruction), &sh.StagehandClientActOptions{Page: page})
|
||||||
|
if err != nil {
|
||||||
|
return tool.ToolResult{Error: fmt.Sprintf("act failed: %v", err)}, nil
|
||||||
|
}
|
||||||
|
out := jsonOutput(res.Data)
|
||||||
|
if !res.Data.Success {
|
||||||
|
return tool.ToolResult{Error: "act did not succeed: " + out}, nil
|
||||||
|
}
|
||||||
|
return tool.ToolResult{Output: out}, nil
|
||||||
|
|
||||||
|
case "observe":
|
||||||
|
var instruction *string
|
||||||
|
if in.Instruction != "" {
|
||||||
|
instruction = &in.Instruction
|
||||||
|
}
|
||||||
|
res, err := sess.client.Observe(ctx, instruction, &sh.StagehandClientObserveOptions{Page: page})
|
||||||
|
if err != nil {
|
||||||
|
return tool.ToolResult{Error: fmt.Sprintf("observe failed: %v", err)}, nil
|
||||||
|
}
|
||||||
|
if len(res.Data) == 0 {
|
||||||
|
return tool.ToolResult{Output: "No matching elements found."}, nil
|
||||||
|
}
|
||||||
|
return tool.ToolResult{Output: jsonOutput(res.Data)}, nil
|
||||||
|
|
||||||
|
case "extract":
|
||||||
|
// Extract derives its schema from a compile-time Go type, so a
|
||||||
|
// caller-supplied schema can't be passed through directly. It is
|
||||||
|
// appended to the instruction instead, and the result is decoded
|
||||||
|
// generically.
|
||||||
|
instruction := in.Instruction
|
||||||
|
if len(in.Schema) > 0 {
|
||||||
|
instruction += "\n\nReturn the data in exactly this JSON Schema shape:\n" + string(in.Schema)
|
||||||
|
}
|
||||||
|
res, err := sh.Extract[map[string]any](ctx, sess.client, instruction, &sh.StagehandClientExtractOptions{Page: page})
|
||||||
|
if err != nil {
|
||||||
|
return tool.ToolResult{Error: fmt.Sprintf("extract failed: %v", err)}, nil
|
||||||
|
}
|
||||||
|
return tool.ToolResult{Output: truncate(jsonOutput(res.Data))}, nil
|
||||||
|
|
||||||
|
case "get_text":
|
||||||
|
text, err := sh.EvaluateAs[string](ctx, page, "document.body ? document.body.innerText : ''")
|
||||||
|
if err != nil {
|
||||||
|
return tool.ToolResult{Error: fmt.Sprintf("get_text failed: %v", err)}, nil
|
||||||
|
}
|
||||||
|
return tool.ToolResult{Output: truncate(text)}, nil
|
||||||
|
|
||||||
|
case "screenshot":
|
||||||
|
opts := &sh.ScreenshotOptions{}
|
||||||
|
if in.FullPage {
|
||||||
|
full := true
|
||||||
|
opts.FullPage = &full
|
||||||
|
}
|
||||||
|
png, err := page.Screenshot(ctx, opts)
|
||||||
|
if err != nil {
|
||||||
|
return tool.ToolResult{Error: fmt.Sprintf("screenshot failed: %v", err)}, nil
|
||||||
|
}
|
||||||
|
url, _ := page.URL(ctx)
|
||||||
|
return tool.ToolResult{
|
||||||
|
Output: fmt.Sprintf("Screenshot of %s (%d bytes)", url, len(png)),
|
||||||
|
Images: []llm.ImageContent{{MimeType: "image/png", Data: png}},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return tool.ToolResult{Error: fmt.Sprintf("unknown action: %q", in.Action)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// acquire returns a locked session and a release func. Named sessions are
|
||||||
|
// created on first use and reused; unnamed calls get a throwaway session
|
||||||
|
// that release tears down.
|
||||||
|
func (t *StagehandTool) acquire(ctx context.Context, name string) (*session, func(), error) {
|
||||||
|
if name == "" {
|
||||||
|
sess, err := t.launch(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return sess, func() { sess.close() }, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
t.mu.Lock()
|
||||||
|
sess, ok := t.sessions[name]
|
||||||
|
if !ok {
|
||||||
|
if len(t.sessions) >= sessionMaxCount {
|
||||||
|
t.mu.Unlock()
|
||||||
|
return nil, nil, fmt.Errorf("too many open sessions (max %d); close one with {\"action\":\"close\",\"session\":\"<name>\"}", sessionMaxCount)
|
||||||
|
}
|
||||||
|
// Launch under t.mu so two concurrent first calls for the same name
|
||||||
|
// don't each start a browser. Launches are rare and bounded by
|
||||||
|
// launchTimeout.
|
||||||
|
var err error
|
||||||
|
sess, err = t.launch(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.mu.Unlock()
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
if t.sessions == nil {
|
||||||
|
t.sessions = make(map[string]*session)
|
||||||
|
}
|
||||||
|
t.sessions[name] = sess
|
||||||
|
t.startJanitorLocked()
|
||||||
|
}
|
||||||
|
t.mu.Unlock()
|
||||||
|
|
||||||
|
sess.mu.Lock()
|
||||||
|
sess.lastUsed = time.Now()
|
||||||
|
return sess, func() {
|
||||||
|
sess.lastUsed = time.Now()
|
||||||
|
sess.mu.Unlock()
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// launchSession starts a browser on the configured backend and attaches a
|
||||||
|
// Stagehand client whose inference runs through the harness provider.
|
||||||
|
func (t *StagehandTool) launchSession(ctx context.Context) (*session, error) {
|
||||||
|
// The browser outlives this call for persistent sessions, so detach it
|
||||||
|
// from the caller's cancellation and bound only the launch itself.
|
||||||
|
launchCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), launchTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
var browser *sh.Browser
|
||||||
|
var err error
|
||||||
|
if t.cfg.BrowserbaseAPIKey != "" {
|
||||||
|
browser, err = sh.LaunchBrowserbase(launchCtx, sh.BrowserbaseLaunchOptions{APIKey: t.cfg.BrowserbaseAPIKey})
|
||||||
|
} else {
|
||||||
|
browser, err = sh.LaunchLocalBrowser(launchCtx, &sh.LocalBrowserLaunchOptions{
|
||||||
|
Headless: !t.cfg.Headful,
|
||||||
|
ExecutablePath: t.cfg.ChromePath,
|
||||||
|
Args: []string{"--host-resolver-rules=" + hostResolverRules},
|
||||||
|
Viewport: &sh.LocalViewport{Width: defaultViewportW, Height: defaultViewportH},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("launch browser: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := sh.Create(launchCtx, sh.CreateOptions{
|
||||||
|
Browser: browser,
|
||||||
|
Generate: NewGenerateFunc(t.cfg.Provider, t.cfg.Model),
|
||||||
|
Logging: &sh.StagehandClientLoggingConfig{Level: sh.StagehandClientLogLevelOff},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
closeCtx, cancelClose := context.WithTimeout(context.Background(), closeTimeout)
|
||||||
|
defer cancelClose()
|
||||||
|
return nil, errors.Join(fmt.Errorf("start stagehand: %w", err), browser.Close(closeCtx))
|
||||||
|
}
|
||||||
|
return &session{browser: browser, client: client, lastUsed: time.Now()}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// close tears down the client then the browser. Safe on a partially
|
||||||
|
// constructed session (tests use sessions with nil fields).
|
||||||
|
func (s *session) close() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), closeTimeout)
|
||||||
|
defer cancel()
|
||||||
|
if s.client != nil {
|
||||||
|
_ = s.client.Close(ctx)
|
||||||
|
}
|
||||||
|
if s.browser != nil {
|
||||||
|
_ = s.browser.Close(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *StagehandTool) closeSession(name string) bool {
|
||||||
|
t.mu.Lock()
|
||||||
|
sess, ok := t.sessions[name]
|
||||||
|
if ok {
|
||||||
|
delete(t.sessions, name)
|
||||||
|
}
|
||||||
|
t.mu.Unlock()
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// Wait for any in-flight call on this session before tearing it down.
|
||||||
|
sess.mu.Lock()
|
||||||
|
defer sess.mu.Unlock()
|
||||||
|
sess.close()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shutdown closes every session and stops the idle janitor. Safe to call
|
||||||
|
// multiple times.
|
||||||
|
func (t *StagehandTool) Shutdown() {
|
||||||
|
t.mu.Lock()
|
||||||
|
all := t.sessions
|
||||||
|
t.sessions = nil
|
||||||
|
if t.stopJanitor != nil {
|
||||||
|
close(t.stopJanitor)
|
||||||
|
t.stopJanitor = nil
|
||||||
|
}
|
||||||
|
t.mu.Unlock()
|
||||||
|
for _, sess := range all {
|
||||||
|
sess.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// startJanitorLocked starts the idle reaper if it isn't running. Caller
|
||||||
|
// holds t.mu.
|
||||||
|
func (t *StagehandTool) startJanitorLocked() {
|
||||||
|
if t.stopJanitor != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
stop := make(chan struct{})
|
||||||
|
t.stopJanitor = stop
|
||||||
|
go func() {
|
||||||
|
ticker := time.NewTicker(janitorInterval)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-stop:
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
t.reapIdle(time.Now())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
// reapIdle closes sessions idle longer than sessionIdleTimeout. A session
|
||||||
|
// whose lock is held is mid-call and therefore not idle.
|
||||||
|
func (t *StagehandTool) reapIdle(now time.Time) {
|
||||||
|
t.mu.Lock()
|
||||||
|
var idle []*session
|
||||||
|
for name, sess := range t.sessions {
|
||||||
|
if !sess.mu.TryLock() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if now.Sub(sess.lastUsed) > sessionIdleTimeout {
|
||||||
|
delete(t.sessions, name)
|
||||||
|
idle = append(idle, sess)
|
||||||
|
} else {
|
||||||
|
sess.mu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.mu.Unlock()
|
||||||
|
for _, sess := range idle {
|
||||||
|
sess.close()
|
||||||
|
sess.mu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func jsonOutput(v any) string {
|
||||||
|
b, err := json.MarshalIndent(v, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Sprintf("%v", v)
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func truncate(s string) string {
|
||||||
|
if len(s) <= maxTextOutput {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return s[:maxTextOutput] + fmt.Sprintf("\n\n[truncated: %d of %d bytes shown]", maxTextOutput, len(s))
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
//go:build live
|
||||||
|
|
||||||
|
package stagehand
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/sausheong/harness/providers/openai"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestLiveStagehandLocalChrome drives a local Chrome through a full
|
||||||
|
// navigate → observe → extract → act → screenshot flow, with Stagehand's
|
||||||
|
// inference routed through the harness OpenAI provider.
|
||||||
|
//
|
||||||
|
// OPENAI_API_KEY=... go test -tags live -run TestLiveStagehand ./tools/stagehand/
|
||||||
|
func TestLiveStagehandLocalChrome(t *testing.T) {
|
||||||
|
key := os.Getenv("OPENAI_API_KEY")
|
||||||
|
if key == "" {
|
||||||
|
t.Skip("OPENAI_API_KEY not set")
|
||||||
|
}
|
||||||
|
model := os.Getenv("STAGEHAND_TEST_MODEL")
|
||||||
|
if model == "" {
|
||||||
|
model = "gpt-4o-mini"
|
||||||
|
}
|
||||||
|
st, err := NewStagehandTool(Config{
|
||||||
|
Provider: openai.NewOpenAIProvider(key, ""),
|
||||||
|
Model: model,
|
||||||
|
BrowserbaseAPIKey: os.Getenv("BROWSERBASE_API_KEY"),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer st.Shutdown()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
run := func(input string) string {
|
||||||
|
t.Helper()
|
||||||
|
res, err := st.Execute(ctx, json.RawMessage(input))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s: %v", input, err)
|
||||||
|
}
|
||||||
|
if res.Error != "" {
|
||||||
|
t.Fatalf("%s: tool error: %s", input, res.Error)
|
||||||
|
}
|
||||||
|
t.Logf("%s\n→ %s", input, res.Output)
|
||||||
|
return res.Output
|
||||||
|
}
|
||||||
|
|
||||||
|
if out := run(`{"action":"navigate","url":"https://example.com","session":"live"}`); !strings.Contains(out, "Example Domain") {
|
||||||
|
t.Errorf("navigate output missing title: %s", out)
|
||||||
|
}
|
||||||
|
run(`{"action":"observe","instruction":"find the links on the page","session":"live"}`)
|
||||||
|
if out := run(`{"action":"extract","instruction":"the main heading of the page","schema":{"type":"object","properties":{"heading":{"type":"string"}}},"session":"live"}`); !strings.Contains(out, "Example Domain") {
|
||||||
|
t.Errorf("extract output missing heading: %s", out)
|
||||||
|
}
|
||||||
|
run(`{"action":"act","instruction":"click the link on the page","session":"live"}`)
|
||||||
|
|
||||||
|
res, err := st.Execute(ctx, json.RawMessage(`{"action":"screenshot","session":"live"}`))
|
||||||
|
if err != nil || res.Error != "" {
|
||||||
|
t.Fatalf("screenshot: %v %s", err, res.Error)
|
||||||
|
}
|
||||||
|
if len(res.Images) != 1 || len(res.Images[0].Data) == 0 {
|
||||||
|
t.Error("screenshot returned no image")
|
||||||
|
}
|
||||||
|
run(`{"action":"close","session":"live"}`)
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
package stagehand
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/sausheong/harness/llm/llmtest"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newTestTool(t *testing.T) *StagehandTool {
|
||||||
|
t.Helper()
|
||||||
|
st, err := NewStagehandTool(Config{Provider: &llmtest.Stub{}, Model: "m"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(st.Shutdown)
|
||||||
|
return st
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewStagehandToolRequiresProviderAndModel(t *testing.T) {
|
||||||
|
if _, err := NewStagehandTool(Config{Model: "m"}); err == nil {
|
||||||
|
t.Error("want error without provider")
|
||||||
|
}
|
||||||
|
if _, err := NewStagehandTool(Config{Provider: &llmtest.Stub{}}); err == nil {
|
||||||
|
t.Error("want error without model")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStagehandParametersIsValidJSON(t *testing.T) {
|
||||||
|
var schema map[string]any
|
||||||
|
if err := json.Unmarshal(newTestTool(t).Parameters(), &schema); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStagehandValidationFailsBeforeLaunch(t *testing.T) {
|
||||||
|
st := newTestTool(t)
|
||||||
|
var launches atomic.Int32
|
||||||
|
st.launch = func(context.Context) (*session, error) {
|
||||||
|
launches.Add(1)
|
||||||
|
return nil, errors.New("should not launch")
|
||||||
|
}
|
||||||
|
cases := map[string]struct {
|
||||||
|
input string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
"missing action": {`{}`, "action is required"},
|
||||||
|
"unknown action": {`{"action":"fly","url":"https://example.com"}`, "unknown action"},
|
||||||
|
"navigate without url": {`{"action":"navigate","session":"s"}`, "url is required"},
|
||||||
|
"act without text": {`{"action":"act","session":"s"}`, "instruction is required"},
|
||||||
|
"extract without text": {`{"action":"extract","url":"https://example.com"}`, "instruction is required"},
|
||||||
|
"bad scheme": {`{"action":"navigate","url":"file:///etc/passwd"}`, "must start with http"},
|
||||||
|
"internal url": {`{"action":"navigate","url":"http://127.0.0.1:8080"}`, "navigate failed"},
|
||||||
|
"no url or session": {`{"action":"screenshot"}`, "without 'url' or 'session'"},
|
||||||
|
"close without name": {`{"action":"close"}`, "session is required"},
|
||||||
|
"schema not object": {`{"action":"extract","instruction":"x","session":"s","schema":[1]}`, "schema must be a JSON object"},
|
||||||
|
"malformed json": {`{`, "invalid input"},
|
||||||
|
}
|
||||||
|
for name, tc := range cases {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
res, err := st.Execute(context.Background(), json.RawMessage(tc.input))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(res.Error, tc.want) {
|
||||||
|
t.Errorf("error = %q, want substring %q", res.Error, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if n := launches.Load(); n != 0 {
|
||||||
|
t.Errorf("browser launched %d times on invalid input", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStagehandLaunchErrorIsReported(t *testing.T) {
|
||||||
|
st := newTestTool(t)
|
||||||
|
st.launch = func(context.Context) (*session, error) { return nil, errors.New("no chrome") }
|
||||||
|
res, err := st.Execute(context.Background(), json.RawMessage(`{"action":"navigate","url":"https://example.com","session":"s"}`))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(res.Error, "no chrome") {
|
||||||
|
t.Errorf("error = %q", res.Error)
|
||||||
|
}
|
||||||
|
if len(st.sessions) != 0 {
|
||||||
|
t.Error("failed launch left a session registered")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStagehandSessionReuseLimitAndClose(t *testing.T) {
|
||||||
|
st := newTestTool(t)
|
||||||
|
var launches atomic.Int32
|
||||||
|
st.launch = func(context.Context) (*session, error) {
|
||||||
|
launches.Add(1)
|
||||||
|
return &session{lastUsed: time.Now()}, nil
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
a1, release, err := st.acquire(ctx, "a")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
release()
|
||||||
|
a2, release, err := st.acquire(ctx, "a")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
release()
|
||||||
|
if a1 != a2 || launches.Load() != 1 {
|
||||||
|
t.Fatalf("named session not reused (launches=%d)", launches.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, name := range []string{"b", "c", "d", "e"} {
|
||||||
|
_, release, err := st.acquire(ctx, name)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
release()
|
||||||
|
}
|
||||||
|
if _, _, err := st.acquire(ctx, "f"); err == nil || !strings.Contains(err.Error(), "too many open sessions") {
|
||||||
|
t.Fatalf("want session limit error, got %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
res, _ := st.Execute(ctx, json.RawMessage(`{"action":"close","session":"a"}`))
|
||||||
|
if !strings.Contains(res.Output, `Closed session "a"`) {
|
||||||
|
t.Errorf("close output = %q", res.Output)
|
||||||
|
}
|
||||||
|
res, _ = st.Execute(ctx, json.RawMessage(`{"action":"close","session":"a"}`))
|
||||||
|
if !strings.Contains(res.Output, "No active session") {
|
||||||
|
t.Errorf("second close output = %q", res.Output)
|
||||||
|
}
|
||||||
|
if _, release, err := st.acquire(ctx, "f"); err != nil {
|
||||||
|
t.Fatalf("slot not freed after close: %v", err)
|
||||||
|
} else {
|
||||||
|
release()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStagehandEphemeralSessionIsNotRegistered(t *testing.T) {
|
||||||
|
st := newTestTool(t)
|
||||||
|
st.launch = func(context.Context) (*session, error) { return &session{}, nil }
|
||||||
|
_, release, err := st.acquire(context.Background(), "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
release()
|
||||||
|
if len(st.sessions) != 0 {
|
||||||
|
t.Error("ephemeral session was registered")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStagehandReapIdleSkipsBusySessions(t *testing.T) {
|
||||||
|
st := newTestTool(t)
|
||||||
|
st.launch = func(context.Context) (*session, error) { return &session{}, nil }
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
_, release, _ := st.acquire(ctx, "idle")
|
||||||
|
release()
|
||||||
|
_, releaseBusy, _ := st.acquire(ctx, "busy")
|
||||||
|
defer releaseBusy()
|
||||||
|
|
||||||
|
st.reapIdle(time.Now().Add(sessionIdleTimeout + time.Minute))
|
||||||
|
|
||||||
|
st.mu.Lock()
|
||||||
|
_, idleLeft := st.sessions["idle"]
|
||||||
|
_, busyLeft := st.sessions["busy"]
|
||||||
|
st.mu.Unlock()
|
||||||
|
if idleLeft {
|
||||||
|
t.Error("idle session not reaped")
|
||||||
|
}
|
||||||
|
if !busyLeft {
|
||||||
|
t.Error("busy session was reaped mid-call")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTruncate(t *testing.T) {
|
||||||
|
long := strings.Repeat("x", maxTextOutput+10)
|
||||||
|
got := truncate(long)
|
||||||
|
if !strings.Contains(got, "[truncated:") || len(got) < maxTextOutput {
|
||||||
|
t.Errorf("truncate produced %d bytes", len(got))
|
||||||
|
}
|
||||||
|
if truncate("short") != "short" {
|
||||||
|
t.Error("short string modified")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,9 +14,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
maxFetchSize = 5 * 1024 * 1024 // 5MB
|
maxFetchSize = 8 * 1024 * 1024 // 8MB raw read; headroom over MaxOutputLength since HTML->markdown shrinks most pages but plain text/JSON responses pass through near 1:1
|
||||||
fetchTimeout = 30 * time.Second
|
fetchTimeout = 30 * time.Second
|
||||||
MaxOutputLength = 50000 // truncate very long pages
|
// MaxOutputLength caps fetched content at roughly 1M tokens, matching
|
||||||
|
// Sonnet 5's context window, using this codebase's own token estimate
|
||||||
|
// of 4 chars/token (see session.Session.EstimateTokens).
|
||||||
|
MaxOutputLength = 4_000_000
|
||||||
)
|
)
|
||||||
|
|
||||||
// WebFetchTool fetches a URL and returns its content as markdown.
|
// WebFetchTool fetches a URL and returns its content as markdown.
|
||||||
|
|||||||
Reference in new issue
Block a user