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
- Variables
- func CostUSD(u Usage) float64
- func DeltaText(prev, cur string) string
- func EstimateTokens(s string) int
- func IsDelta(s string) bool
- func RunCLI(args []string, in io.Reader, out io.Writer) int
- func TruncateSnapshot(s string, maxTokens int) (string, bool)
- type APIError
- type Agent
- func (a *Agent) CacheStats() CacheStats
- func (a *Agent) Close()
- func (a *Agent) PrefixTokenEstimate() int
- func (a *Agent) Prewarm(ctx context.Context) (time.Duration, error)
- func (a *Agent) Reset()
- func (a *Agent) Resume(note string)
- func (a *Agent) Run(ctx context.Context, text string, emit func(Event)) (RunStats, error)
- func (a *Agent) SetPageVisibility(origin string, allowed bool)
- func (a *Agent) Start(ctx context.Context, text string) (string, <-chan Event, error)
- func (a *Agent) Stop()
- func (a *Agent) TakeControl()
- type Backend
- type Block
- type CacheStats
- type Client
- type CompactConfig
- type Config
- type ConfirmKind
- type ConfirmRequest
- type Event
- type EventKind
- type Handler
- type Message
- type Metrics
- type RPCBackend
- func (b *RPCBackend) Act(ctx context.Context, steps []Step) (Result, error)
- func (b *RPCBackend) Close()
- func (b *RPCBackend) CloseTab(id string) error
- func (b *RPCBackend) Confirm(ctx context.Context, req ConfirmRequest) (bool, error)
- func (b *RPCBackend) OpenTab(url string) (TabInfo, error)
- func (b *RPCBackend) Screenshot(tabID string) ([]byte, error)
- func (b *RPCBackend) Snapshot(tabID string, delta bool) (string, error)
- func (b *RPCBackend) StartBackgroundPump()
- func (b *RPCBackend) SwitchTab(id string) error
- func (b *RPCBackend) Tabs() []TabInfo
- func (b *RPCBackend) Title(tabID string) string
- func (b *RPCBackend) URL(tabID string) string
- type Result
- type Risk
- type RunStats
- type Step
- type StepResult
- type TabInfo
- type ThinkingMode
- type Usage
- type UserAsker
Constants ¶
const ( 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.
const DefaultBaseURL = "https://api.anthropic.com"
DefaultBaseURL is the Messages API origin.
const DefaultModel = "claude-haiku-5-5"
DefaultModel is the model the agent targets.
const DeltaPrefix = "# delta"
DeltaPrefix starts every delta snapshot (see diff.go).
Variables ¶
var ErrBusy = errors.New("agent: a run is already active")
ErrBusy is returned by Run/Start while another run is active.
Functions ¶
func CostUSD ¶
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 ¶
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 ¶
EstimateTokens is a cheap token estimate (about 4 bytes per token for English/markup, which slightly over-estimates snapshot YAML).
func RunCLI ¶
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 ¶
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).
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent runs tasks against a Backend.
func (*Agent) CacheStats ¶
func (a *Agent) CacheStats() CacheStats
CacheStats returns cumulative prompt-cache statistics.
func (*Agent) PrefixTokenEstimate ¶
PrefixTokenEstimate estimates the static cache prefix (tools + system).
func (*Agent) Resume ¶
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) SetPageVisibility ¶
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 ¶
Start runs a task asynchronously. Events arrive on the returned channel, which is closed after the terminal done/error event.
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 ¶
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) Prewarm ¶
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 ¶
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
MaxStepsPerAct int // default 30
// Context management.
SnapshotMaxTokens int // cap per snapshot; default 6000
ExtractMaxChars int // cap per extract result; default 8000
// NoInitialObservation: do not put an observation of the current tab next to the task. By default the
// first user message of a run carries the snapshot (or the delta, on a page already read) of the page the
// run starts on, which saves the read_page round trip almost every task began with.
NoInitialObservation bool
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.
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) Close ¶
func (b *RPCBackend) Close()
Close stops the background pump (the engine is the caller's to close).
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) StartBackgroundPump ¶
func (b *RPCBackend) StartBackgroundPump()
StartBackgroundPump keeps the pages running between calls for a while (rpc.Server.BackgroundPump), as the CLI's daemon does: what a page still does after a load or an action (hydrating, rendering a route, answers arriving) progresses while the model thinks instead of in the settle of the next action. For a headless engine only (sweef agent): a window drives its own tabs. Close stops it.
func (*RPCBackend) SwitchTab ¶
func (b *RPCBackend) SwitchTab(id string) error
SwitchTab implements Backend.
func (*RPCBackend) Title ¶
func (b *RPCBackend) Title(tabID string) string
Title 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"`
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 ¶
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).