browser

package
v0.110.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: AGPL-3.0 Imports: 35 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 browser runs browser tasks for channels that have no API (plans/brand-agent, "Browser automation"; docs/browser-workers.md). A task is a capability: the brand, the account it may sign in as, the hosts it may reach, what it may do, the content it may type, and ceilings on steps, time and AI spend. The worker enforces the boundary itself, on every request the browser makes, never through the model's instructions. Secrets come from the account vault for one authorised use and never reach the model: not in context, page text, logs, errors or reports. The browser runs on the operator's own compute (Chrome on the worker's host); no hosted browser vendor and no third-party key.

Index

Constants

View Source
const (
	OpRead   = "read"    // open pages and read them
	OpAct    = "act"     // click, type approved content, submit
	OpSignIn = "sign_in" // sign in as the task's account, from the vault
)

Operations a task may be given.

View Source
const (
	StatusDone          = "done"
	StatusFailed        = "failed"
	StatusWaitingPerson = "waiting_person"
)

Outcome statuses.

View Source
const (
	SessionSave  = "save"
	SessionClear = "clear"
	SessionLeave = ""
)

Session decisions after a run.

View Source
const AITask = "browser_tasks"

AITask is the AI usage task browser runs are booked under.

View Source
const JobTask = "browser.task"

JobTask runs one browser task. Only a process with a browser handles it (OUTFLARE_ROLE=browser, or any working role with Chrome on the host), so on an install without one, tasks wait in the queue and the outflare_browser_tasks_queued metric says so.

View Source
const SecretSession = "session"

SecretSession is the vault kind a saved session lives under.

View Source
const SessionMaxAge = 30 * 24 * time.Hour

SessionMaxAge is how long a saved session is used before the task signs in again from scratch.

Variables

View Source
var ErrOutside = errors.New("outside the task's boundary")

ErrOutside means a URL is outside the task's boundary.

View Source
var ErrSessionStale = errors.New("the saved session is too old to use")

ErrSessionStale means a saved session is too old or unreadable; the task signs in from scratch.

View Source
var Operations = []string{OpRead, OpAct, OpSignIn}

Operations lists them, for the API's checks.

Functions

func Enqueue

func Enqueue(ctx context.Context, q jobs.Querier, ws, taskID string) error

Enqueue queues a task, in the transaction that created or resumed it.

func FindChrome

func FindChrome() string

FindChrome returns the first Chrome or Chromium on PATH, or "".

func HostIn

func HostIn(host string, hosts []string) bool

HostIn reports whether host is one of hosts or under one of them.

func NormalizeHost

func NormalizeHost(h string) string

NormalizeHost lowercases a host and strips a port, scheme and path, so "https://Example.com:443/x" and "example.com" are the same host.

func Resume

func Resume(ctx context.Context, tx pgx.Tx, takeoverID string) (int, error)

Resume queues the tasks that waited on a takeover a person handed back, in the handback's transaction. It returns how many.

func SessionAfter added in v0.83.0

func SessionAfter(out Outcome) string

SessionAfter says what a run's ending does to the account's saved session: a finished run that confirmed the account's identity saves it, a run that found the account unusable at any point (the wrong identity, locked, a refused credential, an expired session) clears it, and anything else leaves it as it was.

func TOTP

func TOTP(seed string, at time.Time) (string, error)

TOTP is the current six-digit code for a base32 seed (RFC 6238, SHA-1, 30-second steps), as authenticator apps compute it. The worker types it for the model, which never sees the seed or the code.

Types

type Boundary

type Boundary struct {
	Hosts []string
	// AllowPrivate lets the browser reach private and loopback addresses
	// and plain http, for tests and local development only.
	AllowPrivate bool
	// Resolver, when set, resolves hosts to check their addresses; nil
	// uses the system resolver.
	Resolver interface {
		LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)
	}
}

Boundary is where a task's browser may go: the hosts it was given (a host matches itself and its subdomains) and the identity providers it signs in through, on the public internet only. Every request the browser makes (navigations, redirects, scripts, images, XHR) is checked against it; the rest is refused at the network, so a page can't send the browser anywhere else.

func (Boundary) Check

func (b Boundary) Check(ctx context.Context, rawURL string) error

Check reports whether the browser may fetch rawURL: a public https address on one of the boundary's hosts. It resolves the host, so a name that points at a private address is refused, and so is every redirect (each one is a request checked on its own).

type Chrome

type Chrome struct {
	// Path is the browser's executable; empty finds one (FindChrome).
	Path string
}

Chrome opens headless Chrome (or Chromium) on this host, one fresh profile per task: no cookies, storage or history from any other task. The task's boundary is enforced by intercepting every request the browser makes and failing the ones outside it, so a page can't fetch, redirect or post anywhere the task wasn't given.

func (Chrome) Open

func (c Chrome) Open(ctx context.Context, b Boundary) (Driver, error)

Open starts a browser for one task.

type Cookie struct {
	Name   string `json:"name"`
	Value  string `json:"value"`
	Domain string `json:"domain"`
	Path   string `json:"path,omitempty"`
	// Expires is seconds since the epoch; 0 for a cookie that lasts the
	// browser session.
	Expires  float64 `json:"expires,omitempty"`
	Secure   bool    `json:"secure,omitempty"`
	HTTPOnly bool    `json:"http_only,omitempty"`
	SameSite string  `json:"same_site,omitempty"`
}

Cookie is one cookie of a saved session.

func Keep added in v0.83.0

func Keep(cookies []Cookie, hosts []string, now time.Time) []Cookie

Keep returns the cookies worth keeping for a task on hosts at now: not expired, and sent to at least one of the hosts (a cookie for .example.com is kept for a task on login.example.com; one for another site is dropped).

type Deps

type Deps struct {
	Driver Driver
	Model  llm.Model
	Price  llm.Price
	// Vault opens one of the task's account's secrets; nil when the task
	// has no account.
	Vault interface {
		Open(ctx context.Context, kind string) (string, error)
	}
	// Accounts records the task's sign-in attempts and asks for a person;
	// nil when the task has no account.
	Accounts interface {
		Record(ctx context.Context, purpose, outcome string, evidence map[string]any) error
		NeedPerson(ctx context.Context, reason, note string) (takeoverID string, err error)
	}
	// Cancelled, when set, says a person cancelled the task meanwhile.
	Cancelled func(ctx context.Context) bool
	// OnStep, when set, is told each step as it happens.
	OnStep func(Step)
	Now    func() time.Time
}

Deps is what a run needs from the rest of the engine.

type Driver

type Driver interface {
	// Navigate opens a URL and waits for the page to load.
	Navigate(ctx context.Context, url string) error
	// Page reads the current page.
	Page(ctx context.Context) (Page, error)
	// Click clicks an element by its ref from the last Page.
	Click(ctx context.Context, ref int) error
	// Type puts text into an element by its ref, replacing what was there,
	// and presses Enter when submit is set.
	Type(ctx context.Context, ref int, text string, submit bool) error
	// Close ends the session and forgets everything it held.
	Close() error
}

Driver is one browser session for one task. The Chrome driver enforces the task's Boundary on every request; a test driver is scripted.

type Element

type Element struct {
	Ref   int    `json:"ref"`
	Role  string `json:"role"` // link, button, textbox, checkbox, select, ...
	Label string `json:"label"`
	Value string `json:"value,omitempty"`
}

Element is something on the page the model may act on, by its ref.

type Opener

type Opener interface {
	Open(ctx context.Context, b Boundary) (Driver, error)
}

Opener starts a browser session inside a boundary.

type Outcome

type Outcome struct {
	Status   string
	Summary  string
	FinalURL string
	Evidence map[string]any
	Steps    []Step
	Usage    llm.Usage
	// TakeoverID is the takeover the task waits for, with waiting_person.
	TakeoverID string
	// SignIns are the sign-in outcomes the run reported, in order; they
	// decide what happens to the account's saved session (SessionAfter).
	SignIns []string
}

Outcome is how a run ended.

func Run

func Run(ctx context.Context, t Task, d Deps) (out Outcome)

Run carries out a task, one model step at a time, until the model finishes, asks for a person, or a ceiling is reached.

type Page

type Page struct {
	URL      string
	Title    string
	Text     string
	Elements []Element
}

Page is what the model sees of the current page: its address, title, visible text and the elements it may act on. Never a screenshot (an image could carry a code or a secret the text scrubber can't see).

func (Page) Render

func (p Page) Render(max int) string

Render is the page as the model reads it, cut to max characters.

type Service

type Service struct {
	Pool   *pgxpool.Pool
	Box    *secrets.Box // the account vault
	Models research.Models
	Opener Opener
	Log    *slog.Logger
	// AllowPrivate lets tasks reach private addresses and plain http
	// (OUTFLARE_BROWSER_ALLOW_PRIVATE), for local development.
	AllowPrivate bool
	Now          func() time.Time
}

Service runs queued tasks in jobs.

func (*Service) Register

func (s *Service) Register(q *jobs.Queue)

Register handles browser tasks on q.

func (*Service) RunTask

func (s *Service) RunTask(ctx context.Context, taskID string) error

RunTask runs a queued task now (the job does this): one run, until the model finishes, asks for a person or hits a ceiling. A task that isn't queued is left alone.

type Session added in v0.83.0

type Session struct {
	SavedAt time.Time `json:"saved_at"`
	Cookies []Cookie  `json:"cookies"`
}

Session is what the vault keeps for an account.

func ParseSession added in v0.83.0

func ParseSession(raw string, now time.Time) (Session, error)

ParseSession reads a saved session; one too old to use, or that can't be read, is ErrSessionStale.

func (Session) Encode added in v0.83.0

func (s Session) Encode() (string, error)

Encode is the session as the vault keeps it, or an error when it is over the size cap.

type SessionKeeper added in v0.83.0

type SessionKeeper interface {
	Cookies(ctx context.Context) ([]Cookie, error)
	SetCookies(ctx context.Context, cookies []Cookie) error
}

SessionKeeper is a Driver whose cookies can be read and set. The Chrome driver is one; a driver that isn't simply never keeps sessions.

type Step

type Step struct {
	N      int            `json:"n"`
	Tool   string         `json:"tool"`
	Input  map[string]any `json:"input"`
	Result string         `json:"result"`
	At     time.Time      `json:"at"`
}

Step is one tool call of a run, as the task's log keeps it: the tool, what it was given (a secret's kind, never its value) and what came back, cut short.

type Task

type Task struct {
	ID, WorkspaceID, BrandID string
	// AccountID is the brand's account the task may sign in as; empty for
	// a task that signs in as nobody.
	AccountID string
	// Goal is what the task is for, written by the agent or a person.
	Goal string
	// Hosts the browser may reach (the account's own and its identity
	// providers' are added by the API).
	Hosts      []string
	Operations []string
	// Content is approved text by name; the model types it by name and
	// never changes it.
	Content map[string]string
	// Ceilings: steps (tool calls), minutes, AI spend in cents.
	MaxSteps   int
	MaxMinutes int
	MaxCents   int64
	// Resumed says a person handled a takeover since the last run.
	Resumed bool
	// SessionRestored says the browser starts with the account's saved
	// session from an earlier run.
	SessionRestored bool
}

Task is the capability a run is given.

Jump to

Keyboard shortcuts

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