agent

package
v0.1.0-alpha.4 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: Apache-2.0 Imports: 27 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package agent is the brain of Sweef's sidebar browser agent: a direct Anthropic Messages API client (net/http + own SSE parser), a tool loop with early dispatch of streamed tool calls, cache-aware context management and prompt-injection defences. It talks to the browser only through Backend.

The agent never imports internal/app or internal/ui; the app implements Backend (or uses RPCBackend over an in-process engine) and forwards Event values to the chrome page as `agent.event`.

Index

Constants

View Source
const (
	OpNavigate   = "navigate"
	OpClick      = "click"
	OpHover      = "hover"
	OpType       = "type"
	OpPress      = "press"
	OpScroll     = "scroll"
	OpWait       = "wait"
	OpSelect     = "select"
	OpBack       = "back"
	OpForward    = "forward"
	OpExtract    = "extract"
	OpScreenshot = "screenshot"
	OpExpect     = "expect"
)

Step ops accepted by the `act` tool.

View Source
const DefaultBaseURL = "https://api.anthropic.com"

DefaultBaseURL is the Messages API origin.

View Source
const DefaultModel = "claude-haiku-5-5"

DefaultModel is the model the agent targets.

View Source
const DeltaPrefix = "# delta"

DeltaPrefix starts every delta snapshot (see diff.go).

Variables

View Source
var ErrBusy = errors.New("agent: a run is already active")

ErrBusy is returned by Run/Start while another run is active.

Functions

func CostUSD

func CostUSD(u Usage) float64

Cost estimates dollars for the given usage. Pricing (Haiku 5.5): $0.10 / $0.50 per MTok in/out up to 100K prompt tokens, $0.50 / $2.50 beyond; cache reads 0.1x and cache writes 1.25x of the input price (the standard 5-minute-TTL multipliers; verify against your invoice).

func DeltaText

func DeltaText(prev, cur string) string

DeltaText renders the difference between two snapshots. Format:

# delta (+ added, - removed; unchanged lines omitted)
@ <closest unchanged line above the change>
- <removed line>
+ <added line>

It returns noChangeText when the snapshots are equal.

func EstimateTokens

func EstimateTokens(s string) int

EstimateTokens is a cheap token estimate (about 4 bytes per token for English/markup, which slightly over-estimates snapshot YAML).

func IsDelta

func IsDelta(s string) bool

IsDelta reports whether s is a delta rendering.

func RunCLI

func RunCLI(args []string, in io.Reader, out io.Writer) int

RunCLI implements `sweef agent "<task>"`: a headless agent run against an in-process engine. args excludes the "agent" word itself. The API key comes from ANTHROPIC_API_KEY (never from flags, so it cannot end up in shell history or process listings); ANTHROPIC_BASE_URL overrides the API origin. It returns the process exit code.

func TruncateSnapshot

func TruncateSnapshot(s string, maxTokens int) (string, bool)

TruncateSnapshot caps a snapshot at about maxTokens tokens. Interactive lines (those carrying a [ref=eN]) are kept first, in document order, which approximates "near the top of the viewport first" because the engine emits the tree in layout order; the rest of the budget goes to non-interactive lines (headings, text) in document order. Output preserves the original order and ends with a notice naming what was dropped.

Types

type APIError

type APIError struct {
	Status     int
	Type       string
	Message    string
	RequestID  string
	RetryAfter time.Duration
}

APIError is an error returned by the API (HTTP status or SSE error event).

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Retryable

func (e *APIError) Retryable() bool

Retryable reports whether the same request may succeed later.

type Agent

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

Agent runs tasks against a Backend.

func New

func New(cfg Config, be Backend) (*Agent, error)

New builds an Agent. cfg.APIKey is required.

func (*Agent) CacheStats

func (a *Agent) CacheStats() CacheStats

CacheStats returns cumulative prompt-cache statistics.

func (*Agent) Close

func (a *Agent) Close()

Close releases idle connections.

func (*Agent) PrefixTokenEstimate

func (a *Agent) PrefixTokenEstimate() int

PrefixTokenEstimate estimates the static cache prefix (tools + system).

func (*Agent) Prewarm

func (a *Agent) Prewarm(ctx context.Context) (time.Duration, error)

Prewarm opens the API connection (call when the sidebar opens).

func (*Agent) Reset

func (a *Agent) Reset()

Reset forgets the conversation (a new chat).

func (*Agent) Resume

func (a *Agent) Resume(note string)

Resume hands the browser back. note describes what the user did or wants (optional); the agent also re-reads the tab list and re-snapshots pages.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, text string, emit func(Event)) (RunStats, error)

Run is the synchronous form of Start; emit receives every event.

func (*Agent) SetPageVisibility

func (a *Agent) SetPageVisibility(origin string, allowed bool)

SetPageVisibility records the user's choice for an origin ("https://x.com" or a bare host). Not-allowed pages are never sent to the model.

func (*Agent) Start

func (a *Agent) Start(ctx context.Context, text string) (string, <-chan Event, error)

Start runs a task asynchronously. Events arrive on the returned channel, which is closed after the terminal done/error event.

func (*Agent) Stop

func (a *Agent) Stop()

Stop aborts the active run (no-op when idle).

func (*Agent) TakeControl

func (a *Agent) TakeControl()

TakeControl pauses the agent: tool calls that have not started return an error, and the loop waits before its next request.

type Backend

type Backend interface {
	// Snapshot returns the accessibility snapshot (snapshot v2 YAML, nodes
	// carry [ref=eN]) of a tab. An empty tabID means the active tab. With
	// delta=true a backend MAY return a compact diff against the previous
	// snapshot it returned (it must then start with DeltaPrefix); the agent
	// core itself always asks for full snapshots and diffs them against the
	// text the model has actually seen, so that find/read_page calls can never
	// desynchronise a backend-side baseline.
	Snapshot(tabID string, delta bool) (string, error)

	// Act runs an ordered batch of steps (each carries its Tab) and returns
	// per-step results. It stops at the first failing non-optional step.
	// OpScreenshot steps are never sent to Act; the agent calls Screenshot.
	Act(ctx context.Context, steps []Step) (Result, error)

	Tabs() []TabInfo
	OpenTab(url string) (TabInfo, error)
	SwitchTab(id string) error
	CloseTab(id string) error

	URL(tabID string) string
	Title(tabID string) string
	Screenshot(tabID string) ([]byte, error)

	// Confirm blocks until the user approves or rejects req (the agent has
	// already emitted an EventConfirm for the UI). A non-nil error counts as a
	// rejection.
	Confirm(ctx context.Context, req ConfirmRequest) (bool, error)
}

Backend is everything the agent needs from the browser. internal/app implements it on top of the engine; RPCBackend is a ready implementation over an in-process *engine.Engine and the rpc Batch runner.

Concurrency: the agent may call Snapshot/URL/Title/Tabs from several goroutines at once (parallel read-only tools, early dispatch), but never issues two Act calls for the same tab concurrently. Implementations must be safe for concurrent use.

Cancellation: Act and Confirm receive the run context. When it is cancelled (user pressed stop) they should return promptly.

type Block

type Block struct {
	Index     int
	Type      string // text, tool_use, thinking, redacted_thinking, ...
	Text      string
	ID        string
	Name      string
	Input     json.RawMessage // tool_use: accumulated input (valid JSON object when InputOK)
	InputOK   bool            // false when the streamed JSON was empty-invalid/truncated
	Thinking  string
	Signature string
	Raw       json.RawMessage // canonical block JSON for the conversation history
}

Block is one completed content block of a streamed assistant message.

type CacheStats

type CacheStats struct {
	Requests      int   `json:"requests"`
	InputTokens   int64 `json:"inputTokens"`
	CacheRead     int64 `json:"cacheReadTokens"`
	CacheCreation int64 `json:"cacheCreationTokens"`
	OutputTokens  int64 `json:"outputTokens"`
}

CacheStats aggregates usage across requests.

func (CacheStats) HitRate

func (c CacheStats) HitRate() float64

HitRate = cache_read / (cache_read + cache_creation + input).

func (CacheStats) Sub

func (c CacheStats) Sub(o CacheStats) CacheStats

Sub returns c minus o (for per-run deltas).

type Client

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

Client is a Messages API client. It is safe for concurrent use.

func NewClient

func NewClient(cfg Config) (*Client, error)

NewClient builds a Client with a tuned transport (HTTP/2, keep-alive, TLS session cache) unless cfg.HTTPClient is supplied.

func (*Client) CacheStats

func (c *Client) CacheStats() CacheStats

CacheStats returns the cumulative usage seen by this client.

func (*Client) Close

func (c *Client) Close()

Close releases idle connections.

func (*Client) Prewarm

func (c *Client) Prewarm(ctx context.Context) (time.Duration, error)

Prewarm opens the TLS (HTTP/2) connection ahead of the first request, e.g. when the sidebar opens. It sends an unauthenticated HEAD to the API origin (no key leaves the process, no tokens are billed); the response status is irrelevant, the point is a pooled, handshaken connection and a cached TLS session. It returns the time it took.

func (*Client) Stream

func (c *Client) Stream(ctx context.Context, body []byte, h *Handler) (*Message, *Metrics, error)

Stream POSTs body (a complete Messages request with stream:true) and parses the SSE response, invoking h as blocks arrive. It retries 429/5xx/overloaded with backoff (honouring retry-after) as long as nothing has been delivered to h yet; after the first content block started a failure is returned with the partial Message so the caller can decide. Cancelling ctx aborts the stream immediately.

type CompactConfig

type CompactConfig struct {
	Disabled         bool
	Every            int // boundary granularity in turns; default 8
	KeepRecentTurns  int // observations from the last N turns are never elided; default 2
	MinPromptTokens  int // below this prompt size compaction is not worth a cache rewrite; default 24000
	HardPromptTokens int // at/above this, elide every old observation; default 60000
}

CompactConfig tunes context compaction.

type Config

type Config struct {
	APIKey  string `json:"-"` // never logged; redacted from every error
	BaseURL string // default https://api.anthropic.com
	Model   string // default claude-haiku-5-5

	Effort           string       // output_config.effort; default "low"
	Thinking         ThinkingMode // default adaptive
	ThoughtSummaries bool         // request thinking.display = "summarized" and emit EventThought
	MaxTokens        int          // per response; default 8192 (thinking tokens count against it; always sent explicitly)

	// Run budgets.
	MaxTurns        int     // default 40
	MaxCostUSD      float64 // default 0.50 per run
	MaxOutputTokens int     // default 60000 per run
	MaxActions      int     // browser steps per run; default 200
	MaxNavigations  int     // navigations per run; default 40
	MaxStepsPerAct  int     // default 30

	// Context management.
	SnapshotMaxTokens int // cap per snapshot; default 6000
	ExtractMaxChars   int // cap per extract result; default 8000
	Compact           CompactConfig

	// Transport.
	HTTPClient   *http.Client                               // optional override
	MaxRetries   int                                        // default 4 (5 attempts)
	RetryBase    time.Duration                              // default 400ms
	RetryMaxWait time.Duration                              // largest retry-after honoured; default 30s
	Sleep        func(context.Context, time.Duration) error // test hook

	Logf func(format string, args ...any) // optional debug sink; never sees the key
}

Config configures a Client and an Agent. The zero value plus an APIKey is valid; defaults are applied by New / NewClient.

func (Config) Format

func (c Config) Format(f fmt.State, verb rune)

Format keeps the API key out of %v / %+v / %#v dumps.

type ConfirmKind

type ConfirmKind string

ConfirmKind classifies why the agent needs the user's approval.

const (
	ConfirmPayment     ConfirmKind = "payment"
	ConfirmMessage     ConfirmKind = "message"
	ConfirmDelete      ConfirmKind = "delete"
	ConfirmCredentials ConfirmKind = "credentials"
	ConfirmCrossDomain ConfirmKind = "cross_domain"
	ConfirmOther       ConfirmKind = "other"
)

type ConfirmRequest

type ConfirmRequest struct {
	RunID   string      `json:"runId"`
	Kind    ConfirmKind `json:"kind"`
	Summary string      `json:"summary"` // human readable, e.g. "Click 'Place order'"
	URL     string      `json:"url,omitempty"`
	Detail  string      `json:"detail,omitempty"`
}

ConfirmRequest asks the user to approve one risky action.

type Event

type Event struct {
	RunID   string          `json:"runId"`
	Kind    EventKind       `json:"kind"`
	Text    string          `json:"text,omitempty"`
	Tool    string          `json:"tool,omitempty"`
	Confirm *ConfirmRequest `json:"confirm,omitempty"`
	Stats   *RunStats       `json:"stats,omitempty"`
}

Event is what the app forwards to the chrome page.

type EventKind

type EventKind string

EventKind mirrors the `kind` of the chrome page's agent.event message.

const (
	EventText    EventKind = "text"    // assistant text delta
	EventThought EventKind = "thought" // thought summary delta (only if Config.ThoughtSummaries)
	EventAction  EventKind = "action"  // human readable label, e.g. "Clicking 'Add to cart'"
	EventStatus  EventKind = "status"  // progress / retry / pause notices
	EventConfirm EventKind = "confirm" // an approval is being requested (answered through Backend.Confirm)
	EventDone    EventKind = "done"
	EventError   EventKind = "error"
)

type Handler

type Handler struct {
	OnText       func(text []byte)
	OnThinking   func(text []byte)
	OnBlockStart func(index int, typ, id, name string)
	OnBlockStop  func(b *Block) // fires for every completed block, tool_use included
	OnRetry      func(attempt int, wait time.Duration, err error)
}

Handler receives streaming callbacks on the goroutine that runs Stream. Byte slices are only valid during the call.

type Message

type Message struct {
	ID           string
	Model        string
	StopReason   string
	StopCategory string
	Blocks       []Block // completed blocks, in index order
	Usage        Usage
	Complete     bool // message_stop was received
}

Message is a (possibly partial, if err != nil) assistant response.

type Metrics

type Metrics struct {
	Attempts      int
	Status        int
	ReusedConn    bool
	Proto         string        // e.g. HTTP/2.0
	Headers       time.Duration // request start -> response headers
	FirstByte     time.Duration // request start -> first SSE byte
	FirstToken    time.Duration // request start -> first text delta (0 if none)
	FirstToolCall time.Duration // request start -> first tool_use block start (0 if none)
	Total         time.Duration
	RequestBytes  int
	ResponseBytes int
	Usage         Usage
	StopReason    string
	RequestID     string
}

Metrics are the timings and counters of one Stream call.

type RPCBackend

type RPCBackend struct {

	// ConfirmFunc answers Confirm. The zero value denies every request.
	ConfirmFunc func(context.Context, ConfirmRequest) (bool, error)
	// contains filtered or unexported fields
}

RPCBackend implements Backend over an in-process engine. Browser actions are executed by rpc.Server's Batch.run (the same verbs as `sweef batch` and the MCP browser_batch tool), snapshots by Page.ariaSnapshot; no engine logic is duplicated here.

func NewRPCBackend

func NewRPCBackend(e *engine.Engine) *RPCBackend

NewRPCBackend wraps e. The engine's existing tabs are visible to the agent.

func (*RPCBackend) Act

func (b *RPCBackend) Act(ctx context.Context, steps []Step) (Result, error)

Act implements Backend by running the steps as one Batch.run.

func (*RPCBackend) CloseTab

func (b *RPCBackend) CloseTab(id string) error

CloseTab implements Backend.

func (*RPCBackend) Confirm

func (b *RPCBackend) Confirm(ctx context.Context, req ConfirmRequest) (bool, error)

Confirm implements Backend.

func (*RPCBackend) OpenTab

func (b *RPCBackend) OpenTab(url string) (TabInfo, error)

OpenTab implements Backend. Like the engine, it returns the usable tab together with the navigation error if the load failed.

func (*RPCBackend) Screenshot

func (b *RPCBackend) Screenshot(tabID string) ([]byte, error)

Screenshot implements Backend (PNG bytes).

func (*RPCBackend) Snapshot

func (b *RPCBackend) Snapshot(tabID string, delta bool) (string, error)

Snapshot implements Backend.

func (*RPCBackend) SwitchTab

func (b *RPCBackend) SwitchTab(id string) error

SwitchTab implements Backend.

func (*RPCBackend) Tabs

func (b *RPCBackend) Tabs() []TabInfo

Tabs implements Backend.

func (*RPCBackend) Title

func (b *RPCBackend) Title(tabID string) string

Title implements Backend.

func (*RPCBackend) URL

func (b *RPCBackend) URL(tabID string) string

URL implements Backend.

type Result

type Result struct {
	OK         bool         `json:"ok"`
	Steps      []StepResult `json:"steps"`
	URL        string       `json:"url,omitempty"`
	Title      string       `json:"title,omitempty"`
	Screenshot []byte       `json:"-"`
	TotalMs    int64        `json:"totalMs"`
}

Result is what Backend.Act returns for a batch of steps.

type Risk

type Risk struct {
	Kind   ConfirmKind
	Reason string
}

Risk is a reason to ask the user before running a step.

type RunStats

type RunStats struct {
	Stop             string  `json:"stop"` // done, end_turn, ask_user, stopped, max_turns, budget, refusal, error
	Turns            int     `json:"turns"`
	Requests         int     `json:"requests"`
	Retries          int     `json:"retries"`
	FirstByteAvgMs   float64 `json:"firstByteAvgMs"`
	TTFTAvgMs        float64 `json:"ttftAvgMs"`
	TTFTP50Ms        float64 `json:"ttftP50Ms"`
	TTFToolAvgMs     float64 `json:"firstToolAvgMs"`
	ToolCalls        int     `json:"toolCalls"`
	ToolAvgMs        float64 `json:"toolAvgMs"`
	ToolTotalMs      int64   `json:"toolTotalMs"`
	Actions          int     `json:"actions"`
	Navigations      int     `json:"navigations"`
	FullSnapshots    int     `json:"fullSnapshots"`
	DeltaSnapshots   int     `json:"deltaSnapshots"`
	Compactions      int     `json:"compactions"`
	Usage            Usage   `json:"usage"`
	CacheHitRate     float64 `json:"cacheHitRate"`
	CostUSD          float64 `json:"costUsd"`
	ElapsedMs        int64   `json:"elapsedMs"`
	ReusedConnection int     `json:"reusedConnections"`
	// DecodeMs is the time spent streaming output (first generated block to
	// message end, summed over requests that produced tokens); OutputTPS is
	// output tokens per second over that time (0 when too short to be meaningful).
	DecodeMs  float64 `json:"decodeMs"`
	OutputTPS float64 `json:"outputTps"`
}

RunStats summarises one run.

type Step

type Step struct {
	Op       string `json:"op"`
	Tab      string `json:"tab,omitempty"` // filled in by the agent
	Ref      string `json:"ref,omitempty"`
	URL      string `json:"url,omitempty"`
	Text     string `json:"text,omitempty"`
	Key      string `json:"key,omitempty"`
	Dir      string `json:"dir,omitempty"`
	Amount   int    `json:"amount,omitempty"`
	Ms       int    `json:"ms,omitempty"`
	Value    string `json:"value,omitempty"`
	Kind     string `json:"kind,omitempty"`
	Append   bool   `json:"append,omitempty"`
	Submit   bool   `json:"submit,omitempty"`
	Optional bool   `json:"optional,omitempty"`
}

Step is one browser action. Which fields matter depends on Op:

navigate   URL
click      Ref
hover      Ref
type       Ref, Text, [Append], [Submit]
press      Key, [Ref]
scroll     [Dir up|down], [Amount px]
wait       Ms | Text | URL (glob)
select     Ref, Value
back/forward
extract    [Ref]  (text content; default: whole body)
screenshot (handled by the agent via Backend.Screenshot)
expect     Kind (text|url|title|visible|hidden|count|value), Value, [Ref]

type StepResult

type StepResult struct {
	Index  int    `json:"index"` // 1-based within the Act call
	Op     string `json:"op"`
	OK     bool   `json:"ok"`
	Output string `json:"output,omitempty"` // e.g. extracted text
	Error  string `json:"error,omitempty"`
	Ms     int64  `json:"ms"`
}

StepResult is the outcome of one Step.

type TabInfo

type TabInfo struct {
	ID     string `json:"id"`
	URL    string `json:"url"`
	Title  string `json:"title"`
	Active bool   `json:"active"`
}

TabInfo describes one browser tab.

type ThinkingMode

type ThinkingMode string

ThinkingMode selects the request's thinking configuration.

const (
	ThinkingAdaptive ThinkingMode = "adaptive" // default (Haiku 5.5 thinks by default)
	ThinkingDisabled ThinkingMode = "disabled" // only valid at effort <= high
)

type Usage

type Usage struct {
	InputTokens         int `json:"input_tokens"`
	OutputTokens        int `json:"output_tokens"`
	CacheCreationTokens int `json:"cache_creation_input_tokens"`
	CacheReadTokens     int `json:"cache_read_input_tokens"`
}

Usage is the token accounting of one request.

func (Usage) PromptTokens

func (u Usage) PromptTokens() int

PromptTokens is every input token the request consumed, cached or not.

type UserAsker

type UserAsker interface {
	Ask(ctx context.Context, question string, options []string) (string, error)
}

UserAsker is an optional Backend extension: when implemented, the ask_user tool blocks for the user's free-form answer instead of ending the run (the default chat flow, where the question is shown and the next user message is the answer).

Jump to

Keyboard shortcuts

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