engine

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 45 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

Index

Constants

View Source
const (
	ContentBoundaryOpen  = "⟦page⟧"
	ContentBoundaryClose = "⟦/page⟧"
)

ContentBoundaryOpen and ContentBoundaryClose are the sentinel markers used to fence untrusted page-derived text when ContentBoundary is enabled. They use Unicode brackets (U+27E6 / U+27E7) that are unlikely to appear in real page content and are visually distinct from tool output.

⟦page⟧ <untrusted text here> ⟦/page⟧
View Source
const (
	ErrCodeStaleRef     = "stale_ref"
	ErrCodeAmbiguousRef = "ambiguous_ref"
	ErrCodeHitTarget    = "hit_target"
	ErrCodeTimeout      = "timeout"
	ErrCodeActionable   = "not_actionable"
	ErrCodePolicy       = "policy"
	ErrCodeUnknown      = "error"
)
View Source
const DefaultActionTimeout = 8 * time.Second

DefaultActionTimeout is the per-operation budget used when the caller does not set a tighter deadline. Kept below typical CLI/SDK read timeouts so a missing element returns a typed error instead of EAGAIN.

View Source
const DefaultSessionName = "default"
View Source
const MobileViewportThreshold = 768

MobileViewportThreshold is the width below which SetViewport switches Chrome to mobile emulation. Callers persisting the resulting profile must use the same threshold or the replayed viewport would differ from the applied one.

View Source
const NavWaitTimeout = 30 * time.Second

NavWaitTimeout is the upper bound for a pre-armed lifecycle wait. Navigation is allowed to exceed DefaultActionTimeout (clicks/types) because a cold page can easily take >8s to reach load.

View Source
const ProtocolVersion = 1

ProtocolVersion is the JSONL/MCP handshake version. Bump when the envelope or core result shapes change incompatibly.

View Source
const (

	// VideoRuntimeStaleAfter bounds how long a persisted recording state can
	// block a new recording when its detached runtime disappeared without
	// publishing a terminal status.
	VideoRuntimeStaleAfter = 5 * time.Second
)

Variables

View Source
var ActivePolicy *policy.Policy

ActivePolicy is the session-wide policy enforced on navigation and actions. Set by the CLI or MCP server at startup. Nil means no restrictions.

View Source
var DefaultDiscoverPorts = []int{9222, 9223, 9224, 9225, 9226, 9227, 9228, 9229}

DefaultDiscoverPorts is the list of common Chrome remote debugging ports scanned by DiscoverCDP when no explicit port is supplied.

View Source
var DefaultExtensionNames = []string{"ublock", "icdc", "force-bg"}

DefaultExtensionNames lists the bundled extension slugs ghostchrome looks for under ~/.ghostchrome/extensions/<name>/ when --default-extensions is set. Mirrors browser-use's defaults.

View Source
var ErrAmbiguousRef = errors.New("ambiguous ref: multiple elements match role+name")

ErrAmbiguousRef means a stale backend node matched more than one live role+name candidate. The agent must re-extract instead of guessing.

View Source
var ErrSessionNotFound = errors.New("session not found in registry")
View Source
var ErrStaleRef = errors.New("stale ref: snapshot is missing or no longer matches the page")

ErrStaleRef indicates that a ref no longer maps to a live element.

Functions

func AcquireContext

func AcquireContext(b *rod.Browser, name string) (*rod.Browser, error)

AcquireContext returns a *rod.Browser view scoped to the named isolated context. It reuses an existing context if the registry entry is still alive in Chrome, otherwise creates a new one and persists it.

The caller must have already connected b to Chrome before calling this.

func AcquireSession

func AcquireSession(name string, opts SessionSpawnOpts) (string, error)

AcquireSession resolves a named session to a browser WebSocket URL. If the session is already running it is reused; otherwise a detached `serve` process is spawned, bound to the disk profile of the same name, and probed until its CDP endpoint is ready.

func AddInitScript

func AddInitScript(srcPath string) (string, error)

AddInitScript copies a JS file into the init-scripts directory.

func AdoptClickPopup

func AdoptClickPopup(page *rod.Page, mark uint64, snapshot *PageSnapshot, ref string) *rod.Page

AdoptClickPopup waits (briefly, only when the last click looked like a popup) for a Target.targetCreated opened by page since mark. Button clicks peek without sleeping.

func ApplyColorScheme

func ApplyColorScheme(page *rod.Page, scheme string) error

ApplyColorScheme emulates prefers-color-scheme. Accepts "dark", "light", "no-preference" (case-insensitive).

func ApplyDefaultPageProfile

func ApplyDefaultPageProfile(page *rod.Page) error

ApplyDefaultPageProfile installs the baseline browser profile used by normal pages. Stealth mode can still layer stronger anti-detection overrides later.

Caller responsibility: do NOT call this on a page belonging to a connected (foreign) Chrome unless the user explicitly opted in via --apply-profile. Mutating an existing user tab's UA / viewport breaks the runtime policy stated in CLAUDE.md.

func ApplyDevice

func ApplyDevice(page *rod.Page, d Device) error

ApplyDevice applies viewport metrics, UA, and touch emulation from a preset.

func ApplyEmulationProfile

func ApplyEmulationProfile(page *rod.Page, s EmulationState) error

ApplyEmulationProfile installs an emulation profile authoritatively.

It differs from ApplyEmulationState, which is a replay helper that only ever adds overrides: this one also turns touch emulation OFF when the profile has Touch=false, so switching from a phone profile back to a desktop one really restores pointer:fine instead of leaving navigator.maxTouchPoints at 5. Use ResetEmulation to drop the overrides entirely.

func ApplyEmulationState

func ApplyEmulationState(page *rod.Page, s EmulationState) error

ApplyEmulationState replays a persisted emulation profile on a page. It is the exact counterpart of what ApplyDevice / SetViewport / ApplyUserAgent installed in the session that saved the profile.

func ApplyInitScriptFiles

func ApplyInitScriptFiles(page *rod.Page, paths []string) error

ApplyInitScriptFiles registers JavaScript files to run before future page scripts. This mirrors Playwright's addInitScript-style behavior for config supplied init scripts.

func ApplyInitScripts

func ApplyInitScripts(page *rod.Page) error

ApplyInitScripts registers installed scripts before scripts on future documents.

func ApplyLocale

func ApplyLocale(page *rod.Page, locale string) error

ApplyLocale emulates Playwright's browser.contextOptions.locale for a page. Without a User-Agent override, CDP has no standalone AcceptLanguage command, so this applies the HTTP header plus navigator.language(s) for new documents.

func ApplyStealth

func ApplyStealth(page *rod.Page) error

ApplyStealth applies anti-detection patches to a page via CDP. Targets DataDome, Akamai, and similar bot-detection systems.

func ApplyTimezone

func ApplyTimezone(page *rod.Page, tz string) error

ApplyTimezone overrides the JavaScript Date/Intl timezone.

func ApplyUserAgent

func ApplyUserAgent(page *rod.Page, ua string) error

ApplyUserAgent overrides navigator.userAgent and the HTTP User-Agent header.

func ApplyUserAgentLocale

func ApplyUserAgentLocale(page *rod.Page, ua string, locale string) error

ApplyUserAgentLocale overrides the User-Agent and optionally the browser Accept-Language value using the same CDP call Playwright-backed contexts use.

func BuildHTTPClient

func BuildHTTPClient(opts HTTPClientOpts) (*http.Client, error)

BuildHTTPClient returns an http.Client honoring the supplied proxy URL. Supports http://, https:// (HTTP CONNECT) and socks5:// schemes. http(s) proxies may carry user:pass; socks5 auth is taken from URL too.

func CaptureMutation

func CaptureMutation(b *Browser, page *rod.Page, prev *PageSnapshot) (SnapshotDiff, *ExtractionResult, error)

CaptureMutation invalidates the extract cache, takes a skeleton snapshot, persists refs, and returns the compact diff against prev.

func CheckHitTarget

func CheckHitTarget(el *rod.Element) error

CheckHitTarget fails when another element would receive the click at the target's center. Label/control pairing is allowed.

func ClassifyError

func ClassifyError(err error) (code string, retryable bool)

ClassifyError maps a failure to a stable code + retry hint.

func CleanupFailedLauncher

func CleanupFailedLauncher(l *launcher.Launcher, removeProfile bool)

CleanupFailedLauncher releases resources after Launcher.Launch returned an error. A non-zero PID means Chrome did start, so wait for Rod's exit channel before deleting. With PID zero no process can still write the generated dir.

func CleanupLauncher

func CleanupLauncher(l *launcher.Launcher, removeProfile bool)

CleanupLauncher synchronously terminates a successfully launched Chrome and optionally removes its Rod-owned temporary profile. Kill must precede Cleanup: Rod's Cleanup waits on the launcher exit channel and has no context or cancellation mechanism of its own.

func ClickDownloadHint

func ClickDownloadHint(page *rod.Page) bool

func ClickElement

func ClickElement(page *rod.Page, el *rod.Element) error

ClickElement performs a click on an already-resolved element (used by the locator path so the same scroll+click+wait logic is shared).

func ClickElementWithButton

func ClickElementWithButton(page *rod.Page, el *rod.Element, button proto.InputMouseButton) error

ClickElementWithButton performs a click with an explicit mouse button.

func ClickNavHint

func ClickNavHint(page *rod.Page) bool

ClickNavHint reports whether the last actionability probe saw an in-page navigation (same-tab link or form submit), not a button that stays put.

func ClickPopupHint

func ClickPopupHint(page *rod.Page) bool

ClickPopupHint reports whether the last click actionability probe on page saw target=_blank or javascript:window.open on the live element.

func ClickRef

func ClickRef(page *rod.Page, ref string, snapshot *PageSnapshot) error

ClickRef clicks the element at the given ref.

func ClickRefWithButton

func ClickRefWithButton(page *rod.Page, ref string, snapshot *PageSnapshot, button proto.InputMouseButton) error

ClickRefWithButton clicks the element at ref with an explicit mouse button.

func CloseContext

func CloseContext(b *rod.Browser, name string) error

CloseContext disposes the named context in Chrome (if alive) and removes it from the registry.

func CloseTab

func CloseTab(browser *rod.Browser, index int) (proto.TargetTargetID, error)

CloseTab closes the tab at the given index.

func CountSelector

func CountSelector(page *rod.Page, selector string) int

CountSelector returns the number of elements matching selector. Errors are swallowed and reported as 0 so the polling caller can distinguish "not-yet-rendered" from "match count below threshold".

func DblClickRef

func DblClickRef(page *rod.Page, ref string, snapshot *PageSnapshot) error

DblClickRef double-clicks the element at the given ref.

func DblClickRefWithButton

func DblClickRefWithButton(page *rod.Page, ref string, snapshot *PageSnapshot, button proto.InputMouseButton) error

DblClickRefWithButton double-clicks an element with an explicit mouse button.

func DefaultExtensionPaths

func DefaultExtensionPaths() ([]string, error)

DefaultExtensionPaths returns absolute paths to the bundled extensions (uBlock Origin Lite, "I still don't care about cookies", Force Background Tab) that exist on disk. Missing entries are silently skipped. When none are found a hint is printed to stderr.

func DefaultExtensionsDir

func DefaultExtensionsDir() (string, error)

DefaultExtensionsDir returns the absolute path to the per-user extensions directory: ~/.ghostchrome/extensions.

func DefaultSession

func DefaultSession() (string, bool)

DefaultSession returns the default attached/session WS URL when it exists and is alive. It does not spawn a new browser.

func DetachSysProcAttr

func DetachSysProcAttr() *syscall.SysProcAttr

DetachSysProcAttr returns platform-specific process attributes for a child that should survive the parent CLI process.

func DetectAgent

func DetectAgent() bool

DetectAgent reports whether the current process runs inside an LLM agent. Detection order:

  1. GHOSTCHROME_PROFILE=agent|human (explicit override).
  2. GHOSTCHROME_AGENT=1|true (explicit opt-in).
  3. Known agent environment variables set by Claude Code, Cursor, Aider, Devin, Gemini CLI, and similar tools.

func DiscoverCDP

func DiscoverCDP(ports []int, timeout time.Duration) (string, error)

DiscoverCDP probes 127.0.0.1 on the given ports for a running Chrome exposing /json/version, and returns the first webSocketDebuggerUrl found. When ports is nil/empty, DefaultDiscoverPorts is used. Returns an error when no endpoint responds within timeout.

func DiscoverCDPChannel

func DiscoverCDPChannel(channel string, ports []int, timeout time.Duration) (string, error)

DiscoverCDPChannel probes local Chrome remote-debugging ports for a browser matching a playwright-cli channel name. It attaches only to already running browsers with remote debugging enabled.

func DragDrop

func DragDrop(page *rod.Page, fromRef, toRef string, snapshot *PageSnapshot, steps int) error

DragDrop drags from one element to another using mouse events.

func DragDropCoords

func DragDropCoords(page *rod.Page, sx, sy, dx, dy float64, steps int) error

DragDropCoords drags from one coordinate to another.

func DropElement

func DropElement(el *rod.Element, payload dropPayload) error

func DropTarget

func DropTarget(page *rod.Page, target string, paths []string, data []DropData, snapshot *PageSnapshot) error

DropTarget dispatches browser drag events on an arbitrary element. Unlike UploadRef, it does not require an <input type=file>: supplied files become File objects in event.dataTransfer and --data values become DataTransfer string entries.

func EnableDialogAutoAccept

func EnableDialogAutoAccept(page *rod.Page)

EnableDialogAutoAccept ensures the page has a dialog listener even when the caller has not configured an explicit policy. Existing explicit policies are preserved across navigation.

func EnsureActionable

func EnsureActionable(el *rod.Element, timeout time.Duration) error

func EnsureTouchEmulation

func EnsureTouchEmulation(page *rod.Page) error

EnsureTouchEmulation turns on touch input emulation so synthesized touch events reach the page. Idempotent: calling it on an already touch-emulated page is a no-op from the page's point of view.

func EvadeRuntimeEnable

func EvadeRuntimeEnable() bool

EvadeRuntimeEnable reports whether Runtime.* subscriptions must be skipped.

func EvalJS

func EvalJS(page *rod.Page, expr string, elementRef string, snapshot *PageSnapshot) (string, error)

EvalJS evaluates JavaScript on the page or in an element context. If elementRef is non-empty, the JS runs with `this` bound to that element.

func EvalJSTimeout

func EvalJSTimeout(page *rod.Page, expr string, elementRef string, snapshot *PageSnapshot, d time.Duration) (string, error)

EvalJSTimeout runs EvalJS with a per-call deadline. When the page's main thread is busy (anti-bot fingerprinting, infinite analytics loop, ...), the underlying CDP Runtime.evaluate call hangs until the deadline fires instead of blocking the server-wide timeout. Returns a typed timeout error the caller can surface clearly to the LLM.

func ExtractNextData

func ExtractNextData(html string) []byte

ExtractNextData scans for the canonical Next.js SSR data island in arbitrary HTML and returns the raw JSON payload. Returns nil when the marker is absent. Exported so callers that obtain HTML through a different path (e.g. Chrome page.HTML()) can reuse the same parser.

func FindSystemChromeBinary

func FindSystemChromeBinary() string

FindSystemChromeBinary returns the absolute path to a real, installed Google Chrome / Chromium binary, or "" if none is found. Preferring the system Chrome over rod's bundled Chromium matters for anti-bot: the bundled build can lag many versions behind, and an outdated Chrome version is itself a signal Cloudflare-style challenges score against.

func FormatDiff

func FormatDiff(d SnapshotDiff) string

FormatDiff renders a SnapshotDiff as compact text.

func FormatErrors

func FormatErrors(errors []ErrorEntry) string

FormatErrors formats errors as compact text lines.

func FormatPlaywrightSnapshot

func FormatPlaywrightSnapshot(result *ExtractionResult) string

FormatPlaywrightSnapshot renders an accessibility tree in the documented playwright-cli snapshot style:

  • heading "Title" [level=1]
  • textbox "Search" [ref=e2]
  • listitem:
  • text: "Item"

func FormatPreview

func FormatPreview(r *PreviewResult) string

FormatPreview renders a compact text report (human profile).

func FormatPreviewProfile

func FormatPreviewProfile(r *PreviewResult, p RenderProfile) string

FormatPreviewProfile renders the preview using the given profile. In agent mode, empty sections and zero-stat headers are dropped, failed requests are grouped by status code and the DOM dump uses one-letter role tags.

func FormatText

func FormatText(result *ExtractionResult) string

FormatText renders the extraction result as compact text (human profile).

func FormatTextProfile

func FormatTextProfile(result *ExtractionResult, p RenderProfile) string

FormatTextProfile renders the extraction result using the given profile. The agent profile uses one-letter role tags, truncates long labels and shortens hrefs (see TruncateURL).

func GetResponseBodyByRequestID

func GetResponseBodyByRequestID(page *rod.Page, requestID string) (string, bool, error)

GetResponseBodyByRequestID fetches a response body from the current CDP session.

func GhostchromeDataDirs

func GhostchromeDataDirs() []string

GhostchromeDataDirs returns the data directories a full uninstall removes: ~/.ghostchrome (profiles, contexts, sessions registry) and the ~/.cache/ghostchrome session-snapshot cache. Missing dirs are omitted.

func HasSelector

func HasSelector(page *rod.Page, selector string) bool

HasSelector reports whether at least one element matches selector. It is a non-throwing alternative to page.Element used by polling loops.

func HistoryStep

func HistoryStep(page *rod.Page, delta int, waitStrategy string) error

HistoryStep runs back/forward with a pre-armed lifecycle wait.

func HoverElement

func HoverElement(page *rod.Page, el *rod.Element) error

HoverElement hovers on an already-resolved element.

func HoverRef

func HoverRef(page *rod.Page, ref string, snapshot *PageSnapshot) error

HoverRef hovers over the element at the given ref.

func HumanMode

func HumanMode() bool

HumanMode reports the current setting.

func InitScriptsDir

func InitScriptsDir() (string, error)

InitScriptsDir returns the directory for user init scripts.

func InternalRef

func InternalRef(ref string) string

InternalRef maps playwright-cli eN refs back to ghostchrome's internal @N refs.

func IsStaticNetworkEntry

func IsStaticNetworkEntry(resourceType, mimeType string) bool

IsStaticNetworkEntry reports whether a request is usually noise for Playwright CLI-style network inspection.

func KillAllSessions

func KillAllSessions() (int, error)

KillAllSessions stops every registered session.

func KillProcess

func KillProcess(pid int) error

KillProcess signals a managed background process.

func LauncherOwnsRodTempProfile

func LauncherOwnsRodTempProfile(l *launcher.Launcher, userDataDir string, launchArgs []string) bool

LauncherOwnsRodTempProfile reports whether the launcher's final user data directory is the ephemeral direct child generated by Rod. Explicit profile inputs are never owned, even when they happen to live under Rod's prefix.

func ListInitScripts

func ListInitScripts() ([]string, error)

ListInitScripts returns the names of installed init scripts.

func LoadFulfillBody

func LoadFulfillBody(value string) ([]byte, error)

LoadFulfillBody returns raw bytes from a @path literal or the string otherwise. Useful so CLI flags can take `"@mock.json"` or an inline payload.

func LoadRules

func LoadRules(rulesPath, baseDir string) ([]compiledRule, error)

LoadRules parses path, validates each rule, loads bodyFile contents, and compiles match patterns. baseDir is used to resolve relative bodyFile paths.

func MatchRule

func MatchRule(rules []compiledRule, url, method string) (*compiledRule, bool)

MatchRule returns the first compiledRule whose pattern and method match url+method. method may be empty to skip method filtering.

func MustReadResponseBody

func MustReadResponseBody(resp *http.Response) ([]byte, error)

MustReadResponseBody is exposed so callers building atypical clients can reuse the gzip handling. We keep readResponseBody (lowercase) for the internal call sites in FastFetch.

func NewLauncher

func NewLauncher(opts LauncherOpts) *launcher.Launcher

NewLauncher returns a configured launcher with the shared anti-detection flags used by both auto-launch (NewBrowser) and the `serve` command. --no-sandbox is auto-enabled when running inside a CI runner (env GITHUB_ACTIONS / CI) or as root, because those environments disable the Chrome sandbox.

func NewTab

func NewTab(browser *rod.Browser, url string) (*rod.Page, error)

NewTab opens a new tab, optionally navigating to url (blank when empty), activates it, and returns the page.

func OpContext

func OpContext(parent context.Context, budget time.Duration) (context.Context, context.CancelFunc)

OpContext returns a per-operation context that cannot outlive parent.

func PageWithBudget

func PageWithBudget(page *rod.Page, budget time.Duration) *rod.Page

PageWithBudget clones page with a per-call Rod timeout. The returned page must not be stored as the long-lived session page.

func ParseBlockList

func ParseBlockList(s string) []string

ParseBlockList splits a comma-separated glob list, trimming spaces and dropping empty entries.

func PlaywrightRef

func PlaywrightRef(ref string) string

PlaywrightRef maps ghostchrome's internal @N refs to playwright-cli's eN refs.

func PopupMark

func PopupMark(page *rod.Page) uint64

PopupMark snapshots the popup-event cursor for page's browser. Call this before a click so TakePopup can see targets created during the action.

func PopupOpenedSince

func PopupOpenedSince(page *rod.Page, before map[string]struct{}) *rod.Page

PopupOpenedSince returns a page that appeared after SnapshotPageTargets.

func PressKey

func PressKey(page *rod.Page, key string, ref string, snapshot *PageSnapshot) error

PressKey sends a keyboard key press. If ref is non-empty, focuses the element first.

func ProbeCDPEndpoint

func ProbeCDPEndpoint(raw string, timeout time.Duration) (string, error)

ProbeCDPEndpoint checks that a CDP HTTP or WebSocket URL still answers /json/version. It never opens a Rod session and therefore never sends Browser.close, which would kill an external Chrome.

func ProfileUsesSystemChrome

func ProfileUsesSystemChrome(userDataDir string) bool

ProfileUsesSystemChrome returns true when the profile dir was created by `ghostchrome import-profile` and is bound to the system Chrome binary. We keep this for backward compatibility but with the cookie decryption path it's no longer required — the bundled Chromium can now read the imported cookies because they were rewritten as plaintext.

func PruneSessions

func PruneSessions() (int, error)

PruneSessions removes registry entries whose Chrome is no longer reachable, killing any lingering serve process and its log. Returns the count pruned.

func RefMayOpenPopup

func RefMayOpenPopup(snapshot *PageSnapshot, ref string) bool

RefMayOpenPopup reports whether clicking this snapshot ref is likely to open a new tab (anchor with target=_blank / window.open / download).

func ReloadPage

func ReloadPage(page *rod.Page, waitStrategy string) error

ReloadPage reloads the current document. The lifecycle waiter is armed before Reload so a cached/fast load cannot outrun WaitForPage.

func RemoveInitScript

func RemoveInitScript(name string) error

RemoveInitScript removes a script by name from the init-scripts directory.

func RemoveProfile

func RemoveProfile(name string) error

RemoveProfile deletes a profile directory. The name is validated and the resolved path is confirmed to live under the profiles dir before any removal, so it can never escape via traversal.

func ResetEmulation

func ResetEmulation(page *rod.Page) error

ResetEmulation drops every emulation override on the page and restores the browser's own User-Agent. Device metrics fall back to the real window size, which is what an un-emulated tab looks like.

func ResolveByLocator

func ResolveByLocator(page *rod.Page, loc Locator) (*rod.Element, error)

ResolveByLocator returns the single visible element matching the locator. Matching strategy:

  • If Text is set: XPath text contains (case-insensitive). Matches <button>, <a>, <label>, generic text containers.
  • Else: extract the a11y tree at skeleton level and filter by (role, name|label).

Zero or multiple visible matches are errors. This strictness is shared by action --by-* flags and generated Playwright locator strings so an ambiguous agent instruction can never silently act on the first element in tree order.

func ResolveCDPEndpoint

func ResolveCDPEndpoint(raw string, timeout time.Duration) (string, error)

ResolveCDPEndpoint returns a browser WebSocket debugger URL for a CDP endpoint. ws:// and wss:// inputs are already resolved; http(s) inputs are probed via /json/version.

func ResolveProfileDir

func ResolveProfileDir(name string) (string, error)

ResolveProfileDir converts a short profile name into the canonical persistent Chrome user_data_dir path under ~/.ghostchrome/profiles/<name>. The directory is created with 0700 perms if missing.

func ResolveRef

func ResolveRef(page *rod.Page, ref string, snapshot *PageSnapshot) (*rod.Element, error)

ResolveRef finds an element by its ref (@1, @2, etc.) using a persisted snapshot.

func ResolveRefSemantic

func ResolveRefSemantic(page *rod.Page, ref string, snapshot *PageSnapshot) (*rod.Element, error)

ResolveRefSemantic resolves @N by backend node id, then by role+name+nth when the node was replaced (typical SPA rerender without navigation).

func ResolveTarget

func ResolveTarget(page *rod.Page, target string, snapshot *PageSnapshot) (*rod.Element, error)

ResolveTarget resolves one interaction target. Targets may be snapshot refs (@N or playwright-cli eN), a strict CSS selector, or the small Playwright locator subset emitted by generate-locator: getByRole, getByText, and getByLabel (with an optional { name: "..." } for getByRole).

CSS selectors must match exactly one element. This deliberately avoids the accidental-first-match behavior that is especially unsafe for agent input.

func RunVideoRuntime

func RunVideoRuntime(ctx context.Context, opts VideoRuntimeOpts) (err error)

RunVideoRuntime continuously records the requested target until a stop file is requested. A file control channel is portable and survives independent CLI processes without trusting a reused PID.

func ScrollBy

func ScrollBy(page *rod.Page, dy int) (int, error)

ScrollBy scrolls by a relative Y offset. Returns the final scrollY.

func ScrollToRef

func ScrollToRef(page *rod.Page, ref string, snapshot *PageSnapshot) error

ScrollToRef scrolls the element at the given ref into view without performing any other interaction.

func ScrollToY

func ScrollToY(page *rod.Page, y int, bottomSentinel bool) (int, error)

ScrollToY scrolls the page to an absolute Y pixel position. When bottomSentinel is true, the page is scrolled to document.body.scrollHeight regardless of the y argument — use this for "scroll-to bottom". Returns the final window.scrollY as observed after the scroll.

func SelectOption

func SelectOption(page *rod.Page, ref string, values []string, snapshot *PageSnapshot) error

SelectOption selects option(s) in a <select> element by visible text.

func SessionLeaseFresh

func SessionLeaseFresh(name string, window time.Duration) bool

func SetCheckedRef

func SetCheckedRef(page *rod.Page, ref string, checked bool, snapshot *PageSnapshot) error

SetCheckedRef brings a checkbox/radio to the desired checked state. It is idempotent: if the element is already in the target state it does nothing, so "check" never accidentally toggles a box that was already ticked.

func SetEvadeRuntimeEnable

func SetEvadeRuntimeEnable(on bool)

SetEvadeRuntimeEnable toggles Runtime.enable evasion process-wide. Wired from the root `--evade-runtime` flag / GHOSTCHROME_EVADE_RUNTIME env.

func SetHumanMode

func SetHumanMode(enabled bool)

SetHumanMode toggles the human-input simulation globally. When false the engine uses the original Rod fast path; when true ClickElement / TypeElement / HoverElement dispatch human-shaped events.

func SetStealthTimezone

func SetStealthTimezone(tz string)

SetStealthTimezone sets the explicit --timezone override applied by ApplyStealth. An empty value falls back to a locale-derived default.

func SetTouchEmulation

func SetTouchEmulation(page *rod.Page, enabled bool) error

SetTouchEmulation toggles Chrome's touch input emulation on a page. It is the exported form of the toggle ApplyDevice uses for touch device presets.

func SetViewport

func SetViewport(page *rod.Page, width, height int) error

SetViewport overrides the page viewport dimensions.

func SnapshotPageTargets

func SnapshotPageTargets(page *rod.Page) map[string]struct{}

SnapshotPageTargets records open page targets so a later PopupOpenedSince can detect a target=_blank / window.open without waiting.

func SnapshotRefNum

func SnapshotRefNum(ref string) (int, bool)

func StartDialogAutoHandler

func StartDialogAutoHandler(page *rod.Page, policy *DialogAutoPolicy)

func StartFileChooserIntercept

func StartFileChooserIntercept(page *rod.Page)

StartFileChooserIntercept prevents native OS file dialogs from blocking clicks on <input type=file>. Upload still uses SetFiles.

func StopPopupWatch

func StopPopupWatch(browser *rod.Browser)

StopPopupWatch cancels the Target.targetCreated subscriber for browser.

func StopSession

func StopSession(name string) error

StopSession terminates the named session's process and removes it from the registry (best-effort: the process may already be gone).

func SubmitOnElement

func SubmitOnElement(page *rod.Page, el *rod.Element) error

SubmitOnElement focuses el and presses Enter on it. TypeElement blurs the field after writing (so change/validation handlers fire), which means a follow-up Enter would otherwise land on document.body — re-focus first so the keydown reaches the input and submits its form.

func SwipeTouch

func SwipeTouch(page *rod.Page, fromX, fromY, toX, toY float64, steps int, duration time.Duration) error

SwipeTouch performs a single-finger swipe from (fromX, fromY) to (toX, toY) in CSS pixels relative to the viewport: touchStart, `steps` touchMove events spread over `duration`, then touchEnd.

Requires touch emulation (see EnsureTouchEmulation); without it Chrome drops the events and the page sees nothing.

func SwitchTab

func SwitchTab(browser *rod.Browser, index int) (*rod.Page, error)

SwitchTab activates the tab at the given index and returns its page.

func TakePopup

func TakePopup(page *rod.Page, mark uint64, wait time.Duration) *rod.Page

TakePopup returns a page opened by page since mark. wait=0 is a non-blocking peek so the button click hot path does not sleep.

func TakeScreenshot

func TakeScreenshot(page *rod.Page, fullPage bool, elementRef string, quality int, snapshot *PageSnapshot) ([]byte, error)

TakeScreenshot captures the page or a specific element. If elementRef is non-empty, captures only that element. If fullPage is true, captures the full scrollable page. quality controls JPEG/WebP quality (1-100); PNG is used if quality <= 0.

func TakeScreenshotFormat

func TakeScreenshotFormat(page *rod.Page, fullPage bool, elementRef string, format string, quality int, snapshot *PageSnapshot) ([]byte, error)

TakeScreenshotFormat is the explicit-format variant. format is "png", "jpeg", "webp", or "" to default (webp when quality > 0, png otherwise). WebP at q=60 is typically 30-50% smaller than JPEG at the same visual quality — preferred when the consumer is an LLM agent that pays per byte.

func TakeScreenshotScaled

func TakeScreenshotScaled(page *rod.Page, fullPage bool, elementRef string, quality int, scale float64, snapshot *PageSnapshot) ([]byte, error)

TakeScreenshotScaled is like TakeScreenshot but accepts a device scale factor. scale <= 0 or == 1 means native resolution. scale = 0.5 halves both dimensions (quartering pixel count and file size).

func TapTouch

func TapTouch(page *rod.Page, x, y float64) error

TapTouch dispatches a touchStart/touchEnd pair at one point — the gesture a mobile page sees when a finger taps it. Use it when a control only reacts to touch events; ordinary clicks remain the default for everything else.

func TouchSessionLease

func TouchSessionLease(name string)

TouchSessionLease records that a client is using the named session so the serve idle reaper will not kill an attached JSONL/MCP/CLI loop.

func TruncateURL

func TruncateURL(u string, maxLen int) string

TruncateURL strips common scheme/www prefixes and shortens the URL to maxLen. Used by formatted output from preview and collect.

func TypeElement

func TypeElement(page *rod.Page, el *rod.Element, text string) error

TypeElement writes text into an already-resolved element.

func TypeFocused

func TypeFocused(page *rod.Page, text string) error

TypeFocused writes text into the currently focused element without changing focus or clearing existing content.

func TypeRef

func TypeRef(page *rod.Page, ref string, text string, snapshot *PageSnapshot) error

TypeRef types text into the element at the given ref. Uses focus + select all + keyboard typing to work with React/Vue/Angular.

func UploadRef

func UploadRef(page *rod.Page, ref string, selector string, files []string, snapshot *PageSnapshot) error

UploadRef sets the files on a file-input element.

The target can be identified either by:

  • ref: a @N reference from the current snapshot (works when the input is a native, visible <input type=file>).
  • selector: a CSS selector (use this when the visible widget is a styled button wrapping a hidden input — common pattern).

Exactly one of ref or selector must be non-empty.

func ValidateExtractLevel

func ValidateExtractLevel(level ExtractLevel) error

ValidateExtractLevel ensures the extraction level is supported.

func VideoRuntimeStatusPath

func VideoRuntimeStatusPath(framesDir string) string

func VideoRuntimeStopPath

func VideoRuntimeStopPath(statusPath string) string

func WaitForAgent

func WaitForAgent(page *rod.Page, b *Browser, snapshot *PageSnapshot, spec WaitSpec, timeout time.Duration) (interface{}, error)

WaitForAgent waits for page/element/text/url conditions used by JSONL and MCP.

func WaitForBotChallenge

func WaitForBotChallenge(page *rod.Page, timeout time.Duration) bool

WaitForBotChallenge detects bot-challenge pages (DataDome, Cloudflare, etc.) and waits for the challenge to clear.

Two behaviours make it materially more reliable than a plain poll loop:

  • Reload of a wedged challenge. Cloudflare hands out an independent challenge token per navigation; an instance that hasn't cleared in ~20s almost never un-sticks on its own, but a fresh reload usually gets a solvable one. We reload up to 3 times within the budget.
  • A one-off pointer nudge. A few Cloudflare variants only progress once the page has observed a genuine input event.

Returns true if a challenge was detected and ultimately cleared.

func WaitForClickDownload

func WaitForClickDownload(page *rod.Page)

WaitForClickDownload peeks for Browser.downloadWillBegin after a click that looked like a file download. Button clicks skip this entirely.

func WaitForClickNavigation

func WaitForClickNavigation(page *rod.Page)

WaitForClickNavigation waits for a same-tab navigation after a click that looked like a link or form submit. Button clicks return immediately.

func WaitForImminentDOM

func WaitForImminentDOM(page *rod.Page, timeout time.Duration) error

WaitForImminentDOM briefly gives an action-triggered DOM update a chance to land. It is intended only for post-mutation snapshot paths.

func WaitForLocator

func WaitForLocator(page *rod.Page, loc Locator, state ElementState, timeout time.Duration) (*rod.Element, error)

WaitForLocator resolves a Locator with retry-until-found-or-stable logic.

It polls every 100 ms with exponential backoff up to 500 ms per interval. Deadline is set by timeout (0 = no wait, resolve once and return).

Returns the resolved element or a timeout/context error.

func WaitForPage

func WaitForPage(page *rod.Page, waitStrategy string) error

WaitForPage applies a supported page wait strategy.

Strategies (ordered fastest → slowest typically):

  • "domcontentloaded": fires when HTML parsed, before sub-resources. ~200-500ms faster than "load" on real-world pages with images/iframes/3P scripts.
  • "load": "load" event — DOM + sub-resources fetched.
  • "stable": DOM mutations have settled for 500ms.
  • "idle": network has been idle for 500ms.
  • "none": return immediately.

Defaults to "domcontentloaded" for empty input — that's the right trade-off for an LLM agent: parsing is done, refs are extractable, but we don't pay for late-loading ads/analytics.

func WaitForRef

func WaitForRef(page *rod.Page, ref string, snapshot *PageSnapshot, state ElementState, timeout time.Duration) (*rod.Element, error)

WaitForRef waits until the element identified by ref in snapshot reaches the desired state.

Refs resolve through ResolveRefSemantic: backendNodeId first, then role+name+nth. Ambiguous matches fail closed (ErrAmbiguousRef).

Returns the resolved element once it satisfies state, or an error.

func WaitForSelector

func WaitForSelector(page *rod.Page, selector string, timeoutSec int) error

WaitForSelector waits for a CSS selector to appear in the DOM.

func WaitForTarget

func WaitForTarget(page *rod.Page, target string, snapshot *PageSnapshot, state ElementState, timeout time.Duration) (*rod.Element, error)

WaitForTarget waits for a ref, strict CSS selector, or supported Playwright locator string. Refs retain their persisted snapshot mapping; CSS selectors and locator strings are resolved afresh while polling.

func WaitForText

func WaitForText(page *rod.Page, needle string, timeout time.Duration) error

WaitForText polls until visible body text contains needle.

func WaitForURL

func WaitForURL(page *rod.Page, needle string, timeout time.Duration) error

WaitForURL polls until the current URL contains needle (substring or glob-lite **).

Types

type APIRequest

type APIRequest struct {
	Method  string            // GET, POST, PUT, DELETE, … (default GET)
	URL     string            // absolute, with query string
	Headers map[string]string // any custom headers
	Body    []byte            // request body, plain bytes
	Timeout time.Duration     // per-request deadline (default 8s)
	Proxy   string            // optional http(s):// or socks5:// proxy URL
}

APIRequest is the cross-method, JSON-aware request shape used by FastFetchAPI. Headers and Body are sent as-is; the helper only owns transport-level details (gzip handling, timeout, JSON detection).

type APIResponse

type APIResponse struct {
	Status        int             `json:"status"`
	URL           string          `json:"url"`
	Headers       http.Header     `json:"headers,omitempty"`
	Body          []byte          `json:"-"`
	BodyText      string          `json:"body_text,omitempty"`
	JSON          json.RawMessage `json:"json,omitempty"`
	IsJSON        bool            `json:"is_json"`
	Elapsed       time.Duration   `json:"-"`
	ElapsedMs     int64           `json:"elapsed_ms"`
	ContentLength int64           `json:"content_length"`
}

APIResponse is what FastFetchAPI returns. Body is the decoded payload (gzip handled). JSON is non-nil when Body parses cleanly as JSON, regardless of the response Content-Type — many APIs lie about the type.

func AlgoliaQuery

func AlgoliaQuery(ctx context.Context, opts AlgoliaOpts) (*APIResponse, error)

AlgoliaQuery is a small convenience wrapper around FastFetchAPI for the common Algolia search shape used by capcar / starterre / aramis-style recipes:

POST https://<appId>-dsn.algolia.net/1/indexes/<index>/query
X-Algolia-Application-Id: <appId>
X-Algolia-API-Key:        <apiKey>
{"params":"<urlencoded form>"}

We construct the params payload from the supplied params map and let FastFetchAPI do the actual HTTP work. Returns the parsed Algolia response (typically `{ hits: [...], nbHits: N, nbPages: P }`).

func FastFetchAPI

func FastFetchAPI(ctx context.Context, req APIRequest) (*APIResponse, error)

FastFetchAPI is the JSON-API counterpart to FastFetch. Use it to replay XHR endpoints captured via `ghostchrome --observe` or to hit a known API directly (Algolia, vendor JSON APIs, public REST). It does not attempt anti-bot detection — APIs that need cookies/tokens fail with a clean status code that the caller acts on.

Differences from FastFetch:

  • generic method (GET/POST/PUT/…)
  • no SSR / __NEXT_DATA__ scanning
  • tries to JSON-parse the body opportunistically; falls back to text

type AlgoliaOpts

type AlgoliaOpts struct {
	AppID        string
	APIKey       string
	Index        string
	Endpoint     string
	Params       map[string]string // raw params, joined with `=&`; alternative to ParamsForm
	ParamsForm   string            // pre-built `query=&hitsPerPage=20&page=0` string
	ExtraHeaders map[string]string
	Timeout      time.Duration
	Proxy        string
}

AlgoliaOpts groups the Algolia-specific knobs. AppID/APIKey/Index are required; Endpoint can be overridden if the site uses a custom DSN.

type Browser

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

Browser wraps a Rod browser with connect/launch logic.

func NewBrowser

func NewBrowser(connectURL string, headless bool, timeoutSec int) (*Browser, error)

NewBrowser creates a browser instance. If connectURL is set, connects to an existing Chrome via CDP. Otherwise, auto-launches a new Chrome process.

func NewBrowserWith

func NewBrowserWith(opts BrowserOpts) (*Browser, error)

NewBrowserWith creates a browser instance with full options. Persistent user_data_dir and upstream proxy only apply in auto-launch mode (i.e., when opts.ConnectURL is empty).

func (*Browser) Alive

func (b *Browser) Alive(d time.Duration) bool

Alive reports whether the underlying Chrome still answers CDP within d. A crashed or killed Chrome leaves the rod handle poisoned — every call on it fails with a context error — so callers holding a long-lived Browser use this cheap probe (one Browser.getVersion round-trip, ~1ms on a live process, instant failure on a dead one) before trusting it.

func (*Browser) AppendConsoleLog

func (b *Browser) AppendConsoleLog(events []ObserverEvent) error

AppendConsoleLog appends console events to the persistent session log.

func (*Browser) AppendNetworkLog

func (b *Browser) AppendNetworkLog(entries []*CapturedEntry) error

AppendNetworkLog appends network entries to the persistent session log.

func (*Browser) BrowserTraceState

func (b *Browser) BrowserTraceState() BrowserTraceState

BrowserTraceState returns the persisted CDP tracing state for this session.

func (*Browser) CachedExtract

func (b *Browser) CachedExtract(page *rod.Page) *ExtractionResult

CachedExtract returns the cached ExtractionResult for the current page if the URL has not changed since the last extraction. Returns nil when no cache exists or the page has navigated. This avoids the expensive CDP AccessibilityGetFullAXTree call when the page content is unchanged.

The URL check uses a lightweight JS eval instead of page.Info() to minimize CDP round-trips.

func (*Browser) ClearConsoleLog

func (b *Browser) ClearConsoleLog() error

ClearConsoleLog removes the persistent console log for this session.

func (*Browser) ClearEmulationState

func (b *Browser) ClearEmulationState() error

ClearEmulationState forgets the persisted emulation profile.

func (*Browser) ClearNetworkLog

func (b *Browser) ClearNetworkLog() error

ClearNetworkLog removes the persistent network log for this session.

func (*Browser) Close

func (b *Browser) Close()

func (*Browser) ConnectURL

func (b *Browser) ConnectURL() string

ConnectURL returns the resolved CDP endpoint used by this browser. Managed sessions and --connect=auto resolve their endpoint before Browser creation, so detached helpers must use this value instead of the original CLI flag.

func (*Browser) Connected

func (b *Browser) Connected() bool

Connected returns true if connected to external Chrome (not launched by us).

func (*Browser) ConsoleLog

func (b *Browser) ConsoleLog() []ObserverEvent

ConsoleLog returns a copy of the persistent console log.

func (*Browser) CurrentTargetID

func (b *Browser) CurrentTargetID() string

CurrentTargetID returns the persisted current tab target, if any.

func (*Browser) DeleteSnapshot

func (b *Browser) DeleteSnapshot(targetID proto.TargetTargetID) error

DeleteSnapshot removes stored ref state for a closed page target.

func (*Browser) EmulationState

func (b *Browser) EmulationState() EmulationState

EmulationState returns the emulation profile persisted for this session.

func (*Browser) InvalidateCachedExtract

func (b *Browser) InvalidateCachedExtract(page *rod.Page) error

InvalidateCachedExtract drops the cached accessibility dump for page so the next snapshot re-extracts after a mutating action. Refs stay in place so click/type can still resolve @N until a fresh extract overwrites them.

func (*Browser) NetworkLog

func (b *Browser) NetworkLog() []*CapturedEntry

NetworkLog returns a copy of the persistent network log.

func (*Browser) Page

func (b *Browser) Page() (page *rod.Page, err error)

Page returns the active page or creates a new one. When connected to an existing Chrome, it prefers the persisted active tab.

func (*Browser) ReacquirePage

func (b *Browser) ReacquirePage(previous *rod.Page) (*rod.Page, error)

ReacquirePage drops the cached page handle and resolves a new live page from the same browser connection. It is intended for long-lived callers (MCP/JSONL) after a target was closed or replaced while Chrome itself is still alive. The previous target's persisted snapshot is discarded so refs from the dead target cannot be used against the replacement page.

ReacquirePage never launches or reconnects Chrome. Callers that cannot recover a page from the current browser must close this Browser and use NewBrowserWith again, which keeps ownership and reconnect semantics explicit.

func (*Browser) RodBrowser

func (b *Browser) RodBrowser() *rod.Browser

RodBrowser returns the underlying rod.Browser for advanced operations.

func (*Browser) SaveSnapshot

func (b *Browser) SaveSnapshot(page *rod.Page, result *ExtractionResult) error

SaveSnapshot persists the latest ref snapshot for the page.

SSRPayloads are stripped from the persisted copy before caching (see stripSSRForCache) — the caller's result, used for the immediate command response, is left untouched; only the copy written to disk is stripped, so a later non-SSR command reading this cache via CachedExtract can never leak SSR data it didn't ask for.

func (*Browser) SetBrowserTraceState

func (b *Browser) SetBrowserTraceState(state BrowserTraceState) error

SetBrowserTraceState stores the CDP tracing state for this session.

func (*Browser) SetCurrentPage

func (b *Browser) SetCurrentPage(page *rod.Page) error

SetCurrentPage marks the provided page as the current tab for the session.

func (*Browser) SetEmulationState

func (b *Browser) SetEmulationState(state EmulationState) error

SetEmulationState persists the emulation profile so the next invocation can replay it. It is a no-op outside managed sessions (one-shot launches keep their overrides for the whole process; foreign Chromes must not be mutated).

func (*Browser) SetVideoState

func (b *Browser) SetVideoState(state VideoState) error

SetVideoState stores video metadata for this session.

func (*Browser) Snapshot

func (b *Browser) Snapshot(page *rod.Page) *PageSnapshot

Snapshot returns the last persisted snapshot for the current page.

func (*Browser) StartBackgroundObserver

func (b *Browser) StartBackgroundObserver(page *rod.Page)

Close cleans up the browser resources. External Chrome keeps running; the CLI process owns the websocket lifetime.

func (*Browser) VideoState

func (b *Browser) VideoState() VideoState

VideoState returns the persisted video metadata for this session.

type BrowserOpts

type BrowserOpts struct {
	ConnectURL     string
	Headless       bool
	Invisible      bool
	TimeoutSec     int
	CDPHeaders     map[string]string
	CDPTimeoutMS   int
	UserDataDir    string   // absolute path; ignored when ConnectURL is set
	Proxy          string   // upstream proxy URL; ignored when ConnectURL is set
	ProxyBypass    string   // Chromium proxy bypass list; ignored when ConnectURL is set
	ExecutablePath string   // Chrome/Chromium binary path; ignored when ConnectURL is set
	LaunchArgs     []string // extra Chromium switches; ignored when ConnectURL is set
	Extensions     []string // absolute paths to unpacked extensions; ignored when ConnectURL is set
	SystemChrome   bool     // force /Applications/Google Chrome.app binary; ignored when ConnectURL is set

	// AttachFresh is set when ConnectURL points at a Chrome we don't own
	// (the user's personal browser, discovered via DiscoverCDP). In that
	// case we must NOT reuse any existing tab — every command works in a
	// freshly created background target so the user's foreground tab is
	// left untouched. Ignored in auto-launch mode.
	AttachFresh bool

	// ContextName, when non-empty, routes all page operations through a
	// named isolated BrowserContext (incognito). The name→contextID mapping
	// is persisted in ~/.ghostchrome/contexts.json across CLI invocations.
	// Only meaningful in connected mode (ConnectURL != ""). In auto-launch
	// mode each process already gets its own profile; the flag is ignored.
	ContextName string

	// TargetTabIndex selects an explicit tab index in connected mode.
	// Nil means "use persisted state or auto-select when unambiguous".
	TargetTabIndex *int

	// ApplyProfile, when true, installs ghostchrome's default UA / viewport
	// profile on whichever page Page() resolves to. In auto-launch mode it
	// is on by default (the page is ours). In connected mode it must be
	// explicit — mutating a foreign Chrome tab violates the runtime policy
	// stated in CLAUDE.md.
	ApplyProfile bool

	// ManagedSession is set when ConnectURL points at a Chrome ghostchrome
	// itself spawned and owns (the transparent daemon or an explicit
	// `-s <name>` session). Only those sessions replay the persisted
	// emulation profile across invocations: doing it on a foreign Chrome
	// would mutate a user tab, which the runtime policy forbids.
	ManagedSession bool

	// ProviderFunc, when set, replaces the local launcher for Chrome
	// provisioning. Returns a WS URL and a cleanup function. Ignored
	// when ConnectURL is set (direct connection takes precedence).
	ProviderFunc func(ctx context.Context) (wsURL string, cleanup func(), err error)
}

BrowserOpts configures NewBrowserWith. It supersedes the positional parameters of NewBrowser and adds persistent profile + upstream proxy support for auto-launch.

type BrowserTraceState

type BrowserTraceState struct {
	Active    bool   `json:"active,omitempty"`
	StartedAt string `json:"started_at,omitempty"`
	Output    string `json:"output,omitempty"`
}

BrowserTraceState tracks whether CDP browser tracing is currently active for a persistent session.

type CaptureSession

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

CaptureSession owns the goroutine that listens to Network events.

func StartCapture

func StartCapture(page *rod.Page, spec CaptureSpec) (*CaptureSession, error)

StartCapture enables the Network domain and begins listening.

func (*CaptureSession) Entries

func (s *CaptureSession) Entries() []*CapturedEntry

Entries returns a snapshot of collected entries.

func (*CaptureSession) ReachedMax

func (s *CaptureSession) ReachedMax() <-chan struct{}

ReachedMax fires once Max matches have been collected.

func (*CaptureSession) Stop

func (s *CaptureSession) Stop() ([]*CapturedEntry, error)

Stop detaches listeners, closes the output file, and returns any write errors.

type CaptureSpec

type CaptureSpec struct {
	// URLMatch is a regex applied to the full request URL. Empty = match all.
	URLMatch string
	// MimeMatch is a regex applied to the response MIME type. Empty = match all.
	MimeMatch string
	// Max is the number of MATCHING entries to collect before ReachedMax fires.
	// 0 = unlimited.
	Max int
	// IncludeBody, when true, fetches the response body via
	// Network.getResponseBody for every matching entry.
	IncludeBody bool
	// ExcludeStatic drops script, stylesheet, font, image, and media requests from
	// matching entries. It is intended for Playwright CLI-compatible network
	// output; raw capture keeps static resources by default.
	ExcludeStatic bool
	// OutputPath, if set, streams each entry as it is captured (NDJSON).
	OutputPath string
}

CaptureSpec configures a passive network capture session. Generic DevTools-Network-tab style recorder: no request modification, no auth bypass — just observation of what the page already requested.

type CapturedEntry

type CapturedEntry struct {
	RequestID    string            `json:"request_id"`
	Method       string            `json:"method"`
	URL          string            `json:"url"`
	ResourceType string            `json:"resource_type"`
	Status       int               `json:"status"`
	StatusText   string            `json:"status_text,omitempty"`
	MimeType     string            `json:"mime_type,omitempty"`
	ReqHeaders   map[string]string `json:"request_headers,omitempty"`
	ResHeaders   map[string]string `json:"response_headers,omitempty"`
	PostData     string            `json:"post_data,omitempty"`
	Body         string            `json:"body,omitempty"`
	BodyBase64   bool              `json:"body_base64,omitempty"`
	BodyError    string            `json:"body_error,omitempty"`
	StartedAt    string            `json:"started_at"`
}

CapturedEntry is one fully-hydrated request/response pair.

type ContextEntry

type ContextEntry struct {
	ID string `json:"id"`
}

ContextEntry maps a user-supplied name to a CDP BrowserContextID.

type ContextRegistryEntry

type ContextRegistryEntry struct {
	Name    string `json:"name"`
	ID      string `json:"id"`
	Alive   bool   `json:"alive"`
	Unknown bool   `json:"unknown,omitempty"` // true when Chrome is unreachable
}

ContextRegistryEntry is the public-facing representation used by the CLI.

func ListContexts

func ListContexts(b *rod.Browser) ([]ContextRegistryEntry, error)

ListContexts returns all registry entries annotated with liveness. b may be nil — in that case all entries are reported as unknown/false.

func (ContextRegistryEntry) AliveStr

func (e ContextRegistryEntry) AliveStr() string

AliveStr returns "yes", "no", or "?" depending on liveness state.

type Device

type Device struct {
	Name      string
	Width     int
	Height    int
	DPR       float64
	UserAgent string
	Mobile    bool
	Touch     bool
}

Device describes a hardware profile used by the emulate command. Dimensions are CSS pixels; DPR is devicePixelRatio.

func DeviceByName

func DeviceByName(name string) (Device, bool)

DeviceByName looks up a Device preset by its canonical name.

func ListDevices

func ListDevices() []Device

ListDevices returns a copy of the registered device presets.

type DialogAutoPolicy

type DialogAutoPolicy struct {
	Accept bool
	Prompt string
	// contains filtered or unexported fields
}

DialogAutoPolicy is mutated in place so JSONL/MCP can change accept/dismiss without restarting the CDP listener. Use Set and Snapshot when accessing it after the handler has started; the handler runs concurrently with callers.

func (*DialogAutoPolicy) Set

func (p *DialogAutoPolicy) Set(accept bool, prompt string)

Set updates the policy atomically from the dialog handler's point of view.

func (*DialogAutoPolicy) Snapshot

func (p *DialogAutoPolicy) Snapshot() (accept bool, prompt string)

Snapshot returns a consistent policy value for one dialog event.

type DialogResult

type DialogResult struct {
	Handled       bool   `json:"handled"`
	Action        string `json:"action"`
	Type          string `json:"type,omitempty"`
	Message       string `json:"message,omitempty"`
	URL           string `json:"url,omitempty"`
	DefaultPrompt string `json:"default_prompt,omitempty"`
	TimedOut      bool   `json:"timed_out,omitempty"`
}

DialogResult describes how a JS dialog handler completed.

func HandleNextDialog

func HandleNextDialog(page *rod.Page, accept bool, promptText string, timeout time.Duration) (*DialogResult, error)

HandleNextDialog waits for the next JavaScript dialog and handles it. The timeout is propagated via context so wait() unblocks cleanly on timeout and no goroutine is leaked.

type DiffEntry

type DiffEntry struct {
	Before DiffNode `json:"before"`
	After  DiffNode `json:"after"`
}

DiffEntry captures a single ref that changed between snapshots.

type DiffNode

type DiffNode struct {
	Ref   string `json:"ref"`
	Role  string `json:"role"`
	Name  string `json:"name,omitempty"`
	Href  string `json:"href,omitempty"`
	Value string `json:"value,omitempty"`
}

DiffNode is the minimal payload we return for added nodes.

type DiffStats

type DiffStats struct {
	AddedCount   int `json:"added"`
	RemovedCount int `json:"removed"`
	ChangedCount int `json:"changed"`
	KeptCount    int `json:"kept"`
}

DiffStats summarises a diff for agent consumption.

type DropData

type DropData struct {
	MIME  string `json:"mime"`
	Value string `json:"value"`
}

DropData is one text entry placed in a DataTransfer object. MIME is the DataTransfer format, for example text/plain or application/json.

type ElementBox

type ElementBox struct {
	X      int `json:"x"`
	Y      int `json:"y"`
	Width  int `json:"width"`
	Height int `json:"height"`
}

ElementBox is a viewport-relative element rectangle in CSS pixels. It is populated only when snapshot --boxes is explicitly requested.

type ElementState

type ElementState string

ElementState describes the desired element state for WaitForLocator.

const (
	// StateAttached waits until the element is present in the DOM.
	StateAttached ElementState = "attached"
	// StateVisible waits until the element is visible (not display:none, not hidden).
	StateVisible ElementState = "visible"
	// StateHidden waits until the element is hidden or removed.
	StateHidden ElementState = "hidden"
	// StateEnabled waits until the element is not disabled.
	StateEnabled ElementState = "enabled"
	// StateStable waits until the element's bounding box stops moving for 100ms.
	StateStable ElementState = "stable"
)

func ParseElementState

func ParseElementState(s string) (ElementState, error)

ParseElementState validates and normalises the string form of a state. Empty string defaults to StateAttached.

type EmulationState

type EmulationState struct {
	Device      string  `json:"device,omitempty"`
	Width       int     `json:"width,omitempty"`
	Height      int     `json:"height,omitempty"`
	DPR         float64 `json:"dpr,omitempty"`
	Mobile      bool    `json:"mobile,omitempty"`
	Touch       bool    `json:"touch,omitempty"`
	UserAgent   string  `json:"user_agent,omitempty"`
	ColorScheme string  `json:"color_scheme,omitempty"`
	Timezone    string  `json:"timezone,omitempty"`
}

EmulationState is the emulation profile of a managed session.

CDP emulation overrides (device metrics, touch, UA, color-scheme, timezone) live in the DevTools session, not in the page: Chrome drops them the moment the client detaches. With the transparent daemon, every CLI invocation is a new short-lived session against a long-lived Chrome, so a viewport set by one command was gone by the next one and the page snapped back to the real window size. Persisting the profile here lets the next command replay it on attach.

func EmulationFromDevice

func EmulationFromDevice(d Device) EmulationState

EmulationFromDevice converts a preset into the persistable profile that ApplyDevice just installed on the page.

func (EmulationState) Empty

func (s EmulationState) Empty() bool

Empty reports whether the profile carries nothing to replay.

func (EmulationState) Summary

func (s EmulationState) Summary() string

Summary renders the profile as a single compact line for CLI feedback.

type ErrorCollector

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

ErrorCollector collects console-side errors from a page via CDP events.

func NewErrorCollector

func NewErrorCollector(page *rod.Page) *ErrorCollector

NewErrorCollector creates a collector and starts listening on the page. It hooks into RuntimeConsoleAPICalled, RuntimeExceptionThrown, and LogEntryAdded. The Log domain carries browser-side messages (CORS, mixed content, CSP violations, deprecation, network ERR_*, cookie warnings) that the Runtime domain does NOT surface — they show up in DevTools Console but go through a different CDP channel. The caller must call Close() to detach the listeners.

func (*ErrorCollector) Close

func (c *ErrorCollector) Close()

Close detaches the error listeners and waits for the dispatch goroutine to drain any in-flight events before returning, so callers that snapshot just before Close see a consistent view.

func (*ErrorCollector) Errors

func (c *ErrorCollector) Errors() []ErrorEntry

Errors returns all collected errors (snapshot).

type ErrorEntry

type ErrorEntry struct {
	Type    string `json:"type"`             // "console" or "network"
	Level   string `json:"level"`            // "error", "warning", "4xx", "5xx"
	Message string `json:"message"`          // error message or URL
	Source  string `json:"source"`           // file:line for console, URL for network
	Status  int    `json:"status,omitempty"` // HTTP status for network errors
	Method  string `json:"method,omitempty"` // HTTP method for network
	TimeMs  int64  `json:"time_ms"`          // timestamp relative to collector start
}

ErrorEntry represents a single console or network error.

func CollectErrors

func CollectErrors(page *rod.Page, url string, waitStrategy string, afterNavigate func(*rod.Page) error) ([]ErrorEntry, error)

CollectErrors navigates if needed and returns console plus network errors.

func ErrorsFromEvents

func ErrorsFromEvents(events []ObserverEvent) []ErrorEntry

ErrorsFromEvents returns the retained console and network errors in an observer history. Reading errors does not consume the session history.

type EventHub

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

EventHub is the single CDP event subscriber for a page session. CLI/JSONL/MCP should reuse this instead of stacking EachEvent loops.

func HubForPage

func HubForPage(page *rod.Page) *EventHub

HubForPage returns the EventHub registered for page, if any.

func StartEventHub

func StartEventHub(page *rod.Page) (*EventHub, error)

StartEventHub enables Network/Page (and Runtime unless evasion is on) and keeps a bounded Drain ring. The live channel is drained so producers never block. Safe to call repeatedly for the same page.

func (*EventHub) Drain

func (h *EventHub) Drain(sinceMS int64) []ObserverEvent

func (*EventHub) Observer

func (h *EventHub) Observer() *Observer

func (*EventHub) Stop

func (h *EventHub) Stop()

func (*EventHub) WaitLifecycle

func (h *EventHub) WaitLifecycle(name proto.PageLifecycleEventName, frame proto.PageFrameID, loader proto.NetworkLoaderID, timeout time.Duration) error

WaitLifecycle blocks until a page lifecycle event matching name/frame/loader is observed. An empty frame or loader matches any.

func (*EventHub) WaitLifecycleSince

func (h *EventHub) WaitLifecycleSince(name proto.PageLifecycleEventName, frame proto.PageFrameID, loader proto.NetworkLoaderID, timeout time.Duration, sinceMS int64) error

type ExtractLevel

type ExtractLevel string

ExtractLevel controls how much of the accessibility tree is returned.

const (
	LevelSkeleton ExtractLevel = "skeleton"
	LevelContent  ExtractLevel = "content"
	LevelFull     ExtractLevel = "full"
)

type ExtractedNode

type ExtractedNode struct {
	Ref           string                 `json:"ref,omitempty"`
	Role          string                 `json:"role"`
	Name          string                 `json:"name,omitempty"`
	Value         string                 `json:"value,omitempty"`
	Level         int                    `json:"level,omitempty"`
	Href          string                 `json:"href,omitempty"`
	Type          string                 `json:"type,omitempty"`
	Checked       *bool                  `json:"checked,omitempty"`
	Disabled      bool                   `json:"disabled,omitempty"`
	Box           *ElementBox            `json:"box,omitempty"`
	BackendNodeID proto.DOMBackendNodeID `json:"-"`
	FrameID       proto.PageFrameID      `json:"-"`
	Children      []ExtractedNode        `json:"children,omitempty"`
}

ExtractedNode represents a filtered accessibility node.

type ExtractionResult

type ExtractionResult struct {
	Nodes []ExtractedNode          `json:"nodes"`
	Refs  map[string]ExtractedNode `json:"refs"`
	Stats ExtractionStats          `json:"stats"`
	// SSRPayloads is populated as a fallback when the accessibility tree
	// comes back empty or fails to load — e.g. an SSR/hydration-driven page
	// (Next.js, Nuxt, ...) still mid-hydration behind an unresolved bot
	// challenge. See ssrFallbackPayloads. Only populated when the caller
	// opts in (includeSSR) — these payloads (__NEXT_DATA__, __APOLLO_STATE__,
	// RSC chunks, ...) can carry tokens/PII on an authenticated page, so they
	// must not be exposed to the LLM by default.
	SSRPayloads []SSRPayload `json:"ssr_payloads,omitempty"`
}

ExtractionResult holds the extraction output.

func Extract

func Extract(page *rod.Page, level ExtractLevel, selector string, includeSSR bool) (*ExtractionResult, error)

Extract retrieves the accessibility tree from the page and filters it. The CDP call uses its own 30 s timeout so a slow navigation doesn't eat into the extraction budget. includeSSR controls whether the SSR-fallback payloads (see ExtractionResult.SSRPayloads) are returned; pass false unless the caller explicitly wants them exposed.

func ExtractWithTimeout

func ExtractWithTimeout(page *rod.Page, level ExtractLevel, selector string, timeout time.Duration, includeSSR bool) (*ExtractionResult, error)

ExtractWithTimeout is like Extract but accepts an explicit timeout for the CDP AccessibilityGetFullAXTree call. Use 0 to inherit the page's context deadline (previous behavior).

func ExtractionForRef

func ExtractionForRef(result *ExtractionResult, ref string) (*ExtractionResult, bool)

ExtractionForRef returns a single-root extraction result for ref.

func LimitExtractionDepth

func LimitExtractionDepth(result *ExtractionResult, maxDepth int) *ExtractionResult

LimitExtractionDepth returns a copy of result whose node children are cut after maxDepth. A negative maxDepth returns result unchanged; 0 keeps only root nodes.

func (ExtractionResult) MarshalJSON

func (r ExtractionResult) MarshalJSON() ([]byte, error)

MarshalJSON serializes the extraction result for the wire: the JSONL `agent` protocol (what the TS/Python SDKs speak), `extract --json`, and the MCP surface. In memory every entry in Refs carries the interactive node's full Children subtree — ExtractionForRef relies on it to scope output to a single ref — but that subtree is already present in Nodes, so serializing it again for every interactive element duplicated a large slice of the payload the agent/SDK receives (the SDK's lightweight RefEntry type never modeled those children). Strip Children from Refs on the wire only; the in-memory struct is left untouched, so ExtractionForRef and other internal readers still see the subtree. Every interactive node already has its own top-level key in Refs, so dropping the nested subtree loses no ref.

type ExtractionStats

type ExtractionStats struct {
	TotalNodes       int `json:"total_nodes"`
	FilteredNodes    int `json:"filtered_nodes"`
	InteractiveCount int `json:"interactive_count"`
}

ExtractionStats provides extraction metrics.

type FastFetchOpts

type FastFetchOpts struct {
	FallbackTLS    bool          // retry a blocked/SSR-empty GET with a Chrome TLS profile before a browser
	UserAgent      string        // "" → derived from runtime.GOOS like ApplyDefaultPageProfile
	AcceptLanguage string        // default "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7"
	Timeout        time.Duration // default 8s
	ExtraHeaders   map[string]string
	Proxy          string // optional http(s):// or socks5:// proxy URL
}

FastFetchOpts tunes the no-browser HTTP path.

type FastResult

type FastResult struct {
	Transport   string // "http" or "http-tls"
	Status      int
	URL         string // final URL after redirects
	HTML        string
	NextData    []byte // raw JSON from <script id="__NEXT_DATA__">; nil if absent
	SSRPayloads []SSRPayload
	Blocked     bool   // anti-bot challenge detected
	Reason      string // human-readable explanation when Blocked or no payload extracted
	Elapsed     time.Duration
}

FastResult is what FastFetch returns. Blocked means "this page is gated by an anti-bot challenge — do NOT trust the body, fall back to a real browser".

NextData is the raw __NEXT_DATA__ JSON when present; SSRPayloads holds the full set of structured data islands found in the body (Next, Nuxt, Apollo, Initial-State, JSON-LD…). Modern recipes pick the first match they understand; legacy callers can keep using NextData.

func FastFetch

func FastFetch(ctx context.Context, url string, opts FastFetchOpts) (*FastResult, error)

FastFetch performs a single GET with realistic browser headers and inspects the response for SSR data and anti-bot markers. It's a best-effort fast path: callers must check (Blocked || NextData == nil) and decide whether to fall back to a Chrome-driven recipe.

type HTTPClientOpts

type HTTPClientOpts struct {
	Proxy   string
	Timeout time.Duration
}

HTTPClientOpts configures the proxy-aware http.Client used by the no-browser commands (fastfetch, fetchapi). Empty Proxy means direct.

type InterceptSession

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

InterceptSession owns the router lifetime. Stop() must be called to release resources.

func StartIntercept

func StartIntercept(browser *rod.Browser, spec InterceptSpec) (*InterceptSession, error)

StartIntercept enables Fetch interception on the browser and returns an InterceptSession. The caller is responsible for Stop().

func (*InterceptSession) Stats

func (s *InterceptSession) Stats() *InterceptStats

Stats returns the live counters.

func (*InterceptSession) Stop

func (s *InterceptSession) Stop() error

Stop disables interception and waits for the background goroutine.

type InterceptSpec

type InterceptSpec struct {
	// BlockPatterns list glob URL patterns to block with
	// NetworkErrorReasonBlockedByClient.
	BlockPatterns []string

	// FulfillPattern optionally matches requests to be answered with the
	// FulfillBody payload and FulfillStatus response code. Only set one pattern.
	FulfillPattern       string
	FulfillBody          []byte
	FulfillStatus        int
	FulfillContentType   string
	FulfillHeaders       map[string]string
	RemoveRequestHeaders []string

	// Rules are pre-compiled rule-file entries. When non-empty, each incoming
	// request is matched against them before falling through to FulfillPattern /
	// BlockPatterns. Populated by LoadRules; callers should not build this slice
	// manually.
	Rules []compiledRule
}

InterceptSpec configures a request interception router.

type InterceptStats

type InterceptStats struct {
	Blocked   int
	Fulfilled int
	Passed    int
	// contains filtered or unexported fields
}

InterceptStats are cumulative counters updated by the router goroutine.

func (*InterceptStats) Snapshot

func (s *InterceptStats) Snapshot() (blocked, fulfilled, passed int)

Snapshot returns a concurrent-safe copy of the counters.

type LauncherOpts

type LauncherOpts struct {
	Headless   bool
	RemotePort int // 0 = random

	// Invisible forces headful Chrome (real rendering pipeline, harder to
	// fingerprint as a bot) but positions the window far off-screen so it
	// stays out of sight. Overrides Headless when set.
	Invisible bool

	// UserDataDir is the absolute Chrome --user-data-dir path. Empty means
	// ephemeral. Use ResolveProfileDir to convert a short profile name into
	// the canonical path under ~/.ghostchrome/profiles/<name>.
	UserDataDir string

	// Proxy is the upstream proxy URL passed to Chrome via --proxy-server.
	// Examples: "http://user:pass@host:port", "socks5://host:1080".
	// Empty means no proxy.
	Proxy string

	// ProxyBypass is passed to Chrome as --proxy-bypass-list when Proxy is set.
	// It uses Chromium's bypass list syntax, matching Playwright's proxy.bypass.
	ProxyBypass string

	// ExecutablePath forces a specific Chrome/Chromium binary. It maps
	// Playwright's browser.launchOptions.executablePath and overrides
	// ghostchrome's system-Chrome preference.
	ExecutablePath string

	// Args are extra Chromium command-line switches, normalized as --flag or
	// --flag=value. They map Playwright's browser.launchOptions.args.
	Args []string

	// Extensions is a list of absolute paths to unpacked Chrome extensions
	// (each path must contain a manifest.json at its root). When non-empty,
	// Chrome is launched with --load-extension and --disable-extensions-except
	// so only the listed extensions are active. Note: requires HeadlessNew
	// (the modern headless mode); old --headless ignores extensions.
	Extensions []string

	// SystemChrome forces the launcher to use the system's Google Chrome
	// binary (com.google.Chrome bundle) instead of rod's bundled Chromium.
	// Required when reusing a profile imported from the user's real Chrome
	// — only com.google.Chrome can decrypt cookies sealed by macOS Keychain
	// "Chrome Safe Storage". Auto-detected via the .ghostchrome-system-chrome
	// marker file in the profile dir.
	SystemChrome bool
}

LauncherOpts configures a stealth-flavored Chrome launcher.

type LifecycleArm

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

LifecycleArm buffers Page.lifecycleEvent until Stop. Arm it before Page.navigate so a fast load cannot outrun the waiter.

func ArmLifecycle

func ArmLifecycle(page *rod.Page) *LifecycleArm

ArmLifecycle enables lifecycle events and starts a persistent listener.

func (*LifecycleArm) Stop

func (a *LifecycleArm) Stop()

func (*LifecycleArm) Wait

Wait blocks until a matching lifecycle event is observed for frame+loader.

type Locator

type Locator struct {
	// Role matches the ARIA role (see engine.interactiveRoles, engine.skeletonRoles).
	// Accepts canonical role strings or their one-letter agent abbreviation
	// ("b"=button, "a"=link, "t"=textbox, etc.).
	Role string

	// Name matches the accessible name. Comparison is case-insensitive and uses
	// substring matching, so "Sign in" matches "Sign in now".
	Name string

	// Label matches the accessible label derived from <label for=...> or
	// aria-labelledby. In Chromium's a11y tree, that's exposed as the name of
	// a textbox / combobox — so this is equivalent to Name for inputs.
	// Included as a separate field for ergonomic CLI flags (--by-label).
	Label string

	// Text matches via page-wide text search — like Playwright's getByText.
	// When set, Role is ignored.
	Text string
}

Locator describes a semantic element match. At least one field must be set. When multiple fields are set, the match is conjunctive (all must hold).

func (Locator) IsEmpty

func (l Locator) IsEmpty() bool

IsEmpty reports whether the locator has no criteria set.

type LocatorMatchCountError

type LocatorMatchCountError struct {
	Description string
	Count       int
}

LocatorMatchCountError identifies a strict semantic-locator cardinality failure. Waiters retry zero matches, but reject ambiguity immediately.

func (*LocatorMatchCountError) Error

func (e *LocatorMatchCountError) Error() string

type NetworkEntry

type NetworkEntry struct {
	Method   string `json:"method,omitempty"`
	URL      string `json:"url"`
	Status   int    `json:"status"`
	Size     int    `json:"size_bytes"`
	TimeMs   int64  `json:"time_ms"`
	MimeType string `json:"mime_type,omitempty"`
	Error    string `json:"error,omitempty"`
}

NetworkEntry represents a captured network request.

type Observer

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

Observer multiplexes CDP Network + Runtime + Page events into a unified channel.

func NewObserver

func NewObserver(page *rod.Page, opts ObserverOpts) *Observer

NewObserver creates an Observer for page. Call Start to begin listening.

func (*Observer) Drain

func (o *Observer) Drain(afterMs int64) []ObserverEvent

Drain returns all events whose TS >= afterMs without removing them.

func (*Observer) Events

func (o *Observer) Events() <-chan ObserverEvent

Events returns the read-only event channel.

func (*Observer) Start

func (o *Observer) Start(ctx context.Context) error

Start enables CDP domains and begins listening. It must be called once.

func (*Observer) Stats

func (o *Observer) Stats() ObserverStats

Stats returns a snapshot of event counters.

func (*Observer) Stop

func (o *Observer) Stop() error

Stop cancels listening, waits for goroutines, and closes the channel. Idempotent.

func (*Observer) WriteNDJSON

func (o *Observer) WriteNDJSON(ctx context.Context, w io.Writer) error

WriteNDJSON streams events from the channel to w as NDJSON until ctx is done or the channel is closed. It flushes after every line if w implements http.Flusher or has a Flush() method.

type ObserverEvent

type ObserverEvent struct {
	TS         int64             `json:"ts"` // unix ms
	Kind       ObserverKind      `json:"kind"`
	Method     string            `json:"method,omitempty"`
	URL        string            `json:"url,omitempty"`
	Status     int               `json:"status,omitempty"`
	MimeType   string            `json:"mime_type,omitempty"`
	Type       string            `json:"type,omitempty"`
	RequestID  string            `json:"request_id,omitempty"`
	Body       string            `json:"body,omitempty"`
	BodyBase64 bool              `json:"body_base64,omitempty"`
	BodyError  string            `json:"body_error,omitempty"`
	Size       int64             `json:"size,omitempty"`
	DurationMs int64             `json:"duration_ms,omitempty"`
	Failed     string            `json:"failed,omitempty"`
	Level      string            `json:"level,omitempty"`
	Text       string            `json:"text,omitempty"`
	Source     string            `json:"source,omitempty"`
	Event      string            `json:"event,omitempty"`
	Frame      string            `json:"frame,omitempty"`
	Loader     string            `json:"loader,omitempty"`
	ReqHeaders map[string]string `json:"request_headers,omitempty"`
	ResHeaders map[string]string `json:"response_headers,omitempty"`
	PostData   string            `json:"post_data,omitempty"`
}

ObserverEvent is one emitted CDP event in a unified format.

type ObserverFilters

type ObserverFilters struct {
	// NetTypes filters by network resource type (e.g. "xhr", "fetch", "document").
	// Empty means accept all.
	NetTypes []string
	// NetURLRegex filters net events by URL. Nil means accept all.
	NetURLRegex *regexp.Regexp
	// ConsoleLevels filters console events (e.g. "error", "warning", "info").
	// Empty means accept all.
	ConsoleLevels []string
	// Kinds limits event kinds emitted. Empty means accept all.
	Kinds []ObserverKind
}

ObserverFilters selectively narrows which events are emitted.

type ObserverKind

type ObserverKind string

ObserverKind classifies an ObserverEvent.

const (
	KindNet     ObserverKind = "net"
	KindConsole ObserverKind = "console"
	KindError   ObserverKind = "error"
	KindPage    ObserverKind = "page"
)

type ObserverOpts

type ObserverOpts struct {
	Filters    ObserverFilters
	MaxEvents  int           // 0 = unlimited
	Duration   time.Duration // 0 = unlimited
	BufferSize int           // channel buffer; default 256
	History    int           // Drain ring size; 0 = default 1000
}

ObserverOpts configures an Observer.

type ObserverStats

type ObserverStats struct {
	Net     int
	Console int
	Error   int
	Page    int
	Total   int
	Dropped int // events discarded due to MaxEvents or channel full
}

ObserverStats holds counters for each kind.

type OpError

type OpError struct {
	Code      string
	Retryable bool
	Err       error
}

OpError is a classified interaction/navigation failure. The JSONL envelope copies Code/Retryable so agents can retry without parsing English error strings.

func (*OpError) Error

func (e *OpError) Error() string

func (*OpError) Unwrap

func (e *OpError) Unwrap() error

type Ownership

type Ownership int

Ownership says what Close/Release is allowed to destroy.

const (
	// OwnershipEphemeral: ghostchrome launched this Chrome and may Browser.close it.
	OwnershipEphemeral Ownership = iota
	// OwnershipManaged: a ghostchrome serve/daemon owns the process. Detach only.
	OwnershipManaged
	// OwnershipAttached: an external Chrome. Never send Browser.close.
	OwnershipAttached
	// OwnershipProvider: a cloud/provider callback owns teardown.
	OwnershipProvider
)

func (Ownership) String

func (o Ownership) String() string

type PageInfo

type PageInfo struct {
	URL    string `json:"url"`
	Title  string `json:"title"`
	Status int    `json:"status"`
	TimeMs int64  `json:"time_ms"`
}

PageInfo holds the result of a navigation.

func Navigate(page *rod.Page, rawURL string, waitStrategy string) (*PageInfo, error)

Navigate goes to the given URL and returns page info.

The lifecycle waiter is registered BEFORE page.Navigate so a fast load cannot outrun it. page.Navigate is used so Rod drops the stale JS context.

type PageSession

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

PageSession is the per-target execution handle: budgets, refs, and actionability live here so CLI/JSONL/MCP share one interaction path.

func (*PageSession) CaptureMutation

func (s *PageSession) CaptureMutation(prev *PageSnapshot) SnapshotDiff

func (*PageSession) Check

func (s *PageSession) Check(ref string, checked bool, snapshot *PageSnapshot) error

func (*PageSession) Click

func (s *PageSession) Click(ref string, snapshot *PageSnapshot, button proto.InputMouseButton) error

func (*PageSession) ClickRef

func (s *PageSession) ClickRef(ref string, snapshot *PageSnapshot) error

func (*PageSession) DblClick

func (s *PageSession) DblClick(ref string, snapshot *PageSnapshot, button proto.InputMouseButton) error

func (*PageSession) Hover

func (s *PageSession) Hover(ref string, snapshot *PageSnapshot) error

func (*PageSession) Page

func (s *PageSession) Page() *rod.Page

func (*PageSession) Select

func (s *PageSession) Select(ref string, values []string, snapshot *PageSnapshot) error

func (*PageSession) Timeout

func (s *PageSession) Timeout() time.Duration

func (*PageSession) Type

func (s *PageSession) Type(ref, text string, snapshot *PageSnapshot) error

type PageSnapshot

type PageSnapshot struct {
	TargetID string                 `json:"target_id"`
	URL      string                 `json:"url,omitempty"`
	Title    string                 `json:"title,omitempty"`
	Refs     map[string]RefSnapshot `json:"refs,omitempty"`
	// CachedExtraction is the last ExtractionResult for this page, persisted so
	// subsequent commands can skip the expensive CDP AccessibilityGetFullAXTree
	// call when the URL has not changed.
	CachedExtraction *ExtractionResult `json:"cached_extraction,omitempty"`
}

PageSnapshot stores the last known interactive refs for a page target.

func BuildSnapshot

func BuildSnapshot(page *rod.Page, result *ExtractionResult) (*PageSnapshot, error)

BuildSnapshot creates an in-memory ref snapshot from an extraction result.

func FillFields

func FillFields(b *Browser, page *rod.Page, fields map[string]string, snapshot *PageSnapshot) (int, *PageSnapshot, error)

FillFields types each ref→value pair in numeric @N order. After every field it rebuilds the snapshot so a country→city cascade cannot click a stale ref.

type PersistentSessionObserver

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

PersistentSessionObserver keeps CDP observation alive in the transparent daemon, including the idle time between short CLI processes.

func StartPersistentSessionObserver

func StartPersistentSessionObserver(connectURL string) (*PersistentSessionObserver, error)

StartPersistentSessionObserver connects a second CDP client to the daemon Chrome and appends bounded network/console events to its session log.

func (*PersistentSessionObserver) Stop

func (p *PersistentSessionObserver) Stop()

Stop detaches observers. Chrome itself remains owned by serve and is not closed through this secondary CDP connection.

type PlaywrightLogState

type PlaywrightLogState struct {
	Console []ObserverEvent `json:"console,omitempty"`
	Network []CapturedEntry `json:"network,omitempty"`
}

PlaywrightLogState stores bounded command-observation buffers for Playwright CLI-compatible console/network inspection.

type PreviewResult

type PreviewResult struct {
	PageInfo *PageInfo         `json:"page"`
	Errors   []ErrorEntry      `json:"errors"`
	Network  []NetworkEntry    `json:"network"`
	DOM      *ExtractionResult `json:"dom"`
	Summary  PreviewSummary    `json:"summary"`
}

PreviewResult is the all-in-one dev report for a page.

func Preview

func Preview(page *rod.Page, url string, waitStrategy string, extractLevel ExtractLevel, afterNavigate func(*rod.Page) error, stealth bool) (*PreviewResult, error)

Preview performs a full page analysis: navigate + collect errors + collect network + extract DOM.

type PreviewSummary

type PreviewSummary struct {
	TotalRequests    int `json:"total_requests"`
	FailedRequests   int `json:"failed_requests"`
	ErrorCount       int `json:"error_count"`
	WarningCount     int `json:"warning_count"`
	InteractiveCount int `json:"interactive_count"`
}

PreviewSummary provides quick stats.

type ProfileGCCandidate

type ProfileGCCandidate struct {
	Name     string    `json:"name"`
	Bytes    int64     `json:"bytes"`
	Modified time.Time `json:"modified"`
}

ProfileGCCandidate is an orphan profile eligible for reclamation.

func GCProfiles

func GCProfiles(ttl time.Duration, dryRun bool) ([]ProfileGCCandidate, error)

GCProfiles finds — and, unless dryRun, deletes — orphan profile directories that are safe to reclaim: never the implicit "default" daemon profile, never a profile backing a currently-live session, and only those idle for at least ttl (no file modified within the window). The idle gate protects persistent login profiles that are still in active rotation even when no session is up right now. Callers should surface the returned candidates before deleting (the CLI defaults to a dry run) so a login profile is never removed silently.

type ProfileInfo

type ProfileInfo struct {
	Name  string `json:"name"`
	Path  string `json:"path"`
	Bytes int64  `json:"bytes"`
}

ProfileInfo describes a persistent Chrome profile on disk (~/.ghostchrome/profiles/<name>).

func ListProfiles

func ListProfiles() ([]ProfileInfo, error)

ListProfiles returns every persistent profile with its on-disk size.

type RefSnapshot

type RefSnapshot struct {
	BackendNodeID proto.DOMBackendNodeID `json:"backend_node_id"`
	Role          string                 `json:"role,omitempty"`
	Name          string                 `json:"name,omitempty"`
	// Nth is the 0-based occurrence of role+name among interactive nodes
	// at snapshot time. Used to re-resolve after a SPA rerender.
	Nth  int    `json:"nth,omitempty"`
	Href string `json:"href,omitempty"`

	FrameID proto.PageFrameID `json:"frame_id,omitempty"`
}

RefSnapshot stores a stable backend node mapping for a single ref.

type RenderProfile

type RenderProfile struct {
	// Agent is true when the output is being consumed by an LLM agent runner
	// (Claude Code, Cursor, Aider, etc.) rather than a human terminal.
	Agent bool

	// Format is "text" or "json".
	Format string

	// MaxLabelLen truncates node names / values to this length in agent mode.
	// 0 means no truncation.
	MaxLabelLen int

	// AbbrevRoles uses 1-2 character role abbreviations (b/a/t/c/s/r/m/x/h).
	AbbrevRoles bool

	// DropEmptyStats omits "[errors] 0 ..." / "[network] ... 0 failed" headers
	// when counts are zero.
	DropEmptyStats bool

	// ContentBoundary wraps page-derived text (node names / values) with sentinel
	// markers so an LLM consuming the snapshot can distinguish tool output from
	// untrusted page content (prompt-injection defense). Default false = opt-in only.
	// Markers used: ⟦page⟧ … ⟦/page⟧
	ContentBoundary bool
}

RenderProfile controls how output is rendered for the calling environment. It is resolved once per CLI invocation (see ResolveProfile) and then threaded into formatters.

func ProfileAgent

func ProfileAgent(format string) RenderProfile

ProfileAgent returns the compact agent-optimised profile.

func ProfileHuman

func ProfileHuman(format string) RenderProfile

ProfileHuman returns the default human-friendly profile.

func ResolveProfile

func ResolveProfile(explicit, format string) RenderProfile

ResolveProfile picks a RenderProfile from an explicit flag ("auto", "human", "agent") with environment-variable fallback for "auto".

type RuleMatchType

type RuleMatchType string

RuleMatchType controls how the match field is interpreted.

const (
	RuleMatchGlob  RuleMatchType = "glob"
	RuleMatchRegex RuleMatchType = "regex"
	RuleMatchExact RuleMatchType = "exact"
)

type RuleSpec

type RuleSpec struct {
	Match       string            `json:"match"`
	MatchType   RuleMatchType     `json:"matchType"`
	Method      string            `json:"method"`
	Status      int               `json:"status"`
	ContentType string            `json:"contentType"`
	Headers     map[string]string `json:"headers"`
	Body        string            `json:"body"`
	BodyFile    string            `json:"bodyFile"`
}

RuleSpec is the JSON schema for one entry in the rules file.

type RulesFile

type RulesFile struct {
	Rules []RuleSpec `json:"rules"`
}

RulesFile is the top-level JSON structure.

type Runtime

type Runtime struct {
	Browser    *Browser
	Ownership  Ownership
	Generation uint64
	// contains filtered or unexported fields
}

Runtime is the session-scoped execution handle. CLI, JSONL and MCP should drive pages through it so ownership, budgets and ref maps stay consistent.

func NewRuntime

func NewRuntime(b *Browser) *Runtime

NewRuntime wraps an existing Browser with explicit ownership inferred from how it was opened. Prefer this over reading Browser.connected.

func (*Runtime) AttachEvents

func (r *Runtime) AttachEvents(page *rod.Page) *EventHub

AttachEvents starts the shared EventHub for page. Call this from long-lived JSONL/MCP sessions; skip it under stealth so we do not send Runtime.enable.

func (*Runtime) Close

func (r *Runtime) Close()

Close stops the event hub then applies Browser ownership rules.

func (*Runtime) EventHub

func (r *Runtime) EventHub() *EventHub

EventHub returns the shared CDP subscriber, if started.

func (*Runtime) PageSession

func (r *Runtime) PageSession(page *rod.Page) *PageSession

PageSession binds a target/page to this runtime.

type SSRPayload

type SSRPayload struct {
	Source SSRSource       `json:"source"`
	Data   json.RawMessage `json:"data"`
	IsJSON bool            `json:"is_json"`
	// Type is set for JSON-LD payloads to surface schema.org @type
	// without forcing the caller to re-parse.
	Type string `json:"type,omitempty"`
}

SSRPayload is one structured data island found in HTML. Data is the raw payload as it appeared in the page — JSON for the *Data sources and JSON-LD, plain JS expression for *State / Nuxt 2. IsJSON tells the caller whether they can json.Unmarshal it directly.

func ExtractRSCPayloads

func ExtractRSCPayloads(html string) []SSRPayload

ExtractRSCPayloads decodes Next.js App Router RSC chunks and returns one SSRPayload per logical entry (`<id>:<value>`). Values that parse as JSON (object, array, string) are surfaced with IsJSON=true; module refs and element trees are returned as raw strings (callers that care can run them through V8 — but the JSON ones cover most data needs).

Stream format reference:

0:["$","html",null,{...}]      RSC element tree
1:I[123,[...],"Comp"]          module / chunk reference
2:[...listings JSON...]        plain JSON data island
3:T82a,Lorem ipsum…            text token

We keep all of them; downstream extractors filter by id or by "starts with `[` / `{`" depending on what they need.

func ExtractSSRPayloads

func ExtractSSRPayloads(html string) []SSRPayload

ExtractSSRPayloads finds every supported SSR data island in the HTML and returns them in order of appearance. Sites that ship multiple frameworks (e.g. Next + Apollo, or several JSON-LD blocks) get one entry per island.

Always-safe: returns nil on absence rather than an error. Callers decide what to do with the empty list (often: fall back to Chrome).

type SSRSource

type SSRSource string

SSRSource classifies the origin of an SSR data payload found in a page's HTML. Different frameworks expose their state in different shapes; we surface the source so downstream tooling can pick a parser per format.

const (
	SourceNextData     SSRSource = "next"          // <script id="__NEXT_DATA__" type="application/json">
	SourceNuxtData     SSRSource = "nuxt"          // <script id="__NUXT_DATA__" type="application/json"> (Nuxt 3)
	SourceNuxtJS       SSRSource = "nuxt-js"       // window.__NUXT__=... (Nuxt 2; raw JS, not JSON)
	SourceApolloState  SSRSource = "apollo"        // window.__APOLLO_STATE__=...
	SourceInitialState SSRSource = "initial-state" // window.__INITIAL_STATE__=...
	SourcePreloaded    SSRSource = "preloaded"     // window.__PRELOADED_STATE__=...
	SourceReduxState   SSRSource = "redux"         // window.__REDUX_STATE__=...
	SourceJSONLD       SSRSource = "jsonld"        // <script type="application/ld+json">
	SourceRSC          SSRSource = "rsc"           // self.__next_f.push([1, "<chunks>"]) (Next.js App Router)
)

type SessionEntry

type SessionEntry struct {
	Name       string `json:"name"`
	Port       int    `json:"port"`
	PID        int    `json:"pid"`
	WSURL      string `json:"ws_url"`
	Profile    string `json:"profile"`
	LaunchedAt string `json:"launched_at"`
}

SessionEntry is one named, auto-managed Chrome in the session registry. A session is a long-lived `serve` process bound to a disk profile of the same name (so cookies persist), reused across CLI invocations.

func AttachSession

func AttachSession(name string, wsURL string) (SessionEntry, error)

AttachSession registers an existing CDP endpoint as a named session. It does not spawn or own the browser process; StopSession removes the registry entry but will not terminate an external browser because PID/Port are zero.

type SessionRegistryEntry

type SessionRegistryEntry struct {
	Name       string `json:"name"`
	Port       int    `json:"port"`
	PID        int    `json:"pid"`
	WSURL      string `json:"ws_url"`
	Profile    string `json:"profile"`
	LaunchedAt string `json:"launched_at,omitempty"`
	Alive      bool   `json:"alive"`
}

SessionRegistryEntry is the public-facing representation used by the CLI.

func ListSessions

func ListSessions() ([]SessionRegistryEntry, error)

ListSessions returns every registry entry annotated with current liveness.

func ResolveSession

func ResolveSession(name string) (SessionRegistryEntry, error)

ResolveSession returns the live browser WebSocket URL for an existing registered session. It never spawns a new browser.

func (SessionRegistryEntry) AliveStr

func (e SessionRegistryEntry) AliveStr() string

AliveStr returns "yes" or "no".

type SessionSpawnOpts

type SessionSpawnOpts struct {
	Headless       bool
	Stealth        bool
	Proxy          string
	ProxyBypass    string
	ExecutablePath string
	ConfigPath     string
}

SessionSpawnOpts carries the global flags propagated to a spawned serve.

type SnapshotDiff

type SnapshotDiff struct {
	Unchanged bool                 `json:"unchanged,omitempty"`
	Added     []DiffNode           `json:"added,omitempty"`
	Removed   []string             `json:"removed,omitempty"`
	Changed   map[string]DiffEntry `json:"changed,omitempty"`
	Stats     DiffStats            `json:"stats"`
}

SnapshotDiff reports the changes between two ref maps of a page. All fields are optional in JSON output so an unchanged page serialises to `{"unchanged":true}`.

func DiffRefs

func DiffRefs(prev, curr map[string]RefSnapshot) SnapshotDiff

DiffRefs compares two ref maps (typically the persisted PageSnapshot.Refs). Refs are reassigned in document order by the extractor, so a key match indicates the same logical node slot. A role or name change on the same key counts as "changed"; disappearing or new keys count as removed/added.

type SnapshotMode

type SnapshotMode string

SnapshotMode controls post-mutation output.

const (
	SnapshotModeNone SnapshotMode = "none"
	SnapshotModeDiff SnapshotMode = "diff"
	SnapshotModeFull SnapshotMode = "full"
)

func ParseSnapshotMode

func ParseSnapshotMode(s string) (SnapshotMode, error)

ParseSnapshotMode accepts none/diff/full. Empty defaults to diff.

type TabInfo

type TabInfo struct {
	Index    int    `json:"index"`
	URL      string `json:"url"`
	Title    string `json:"title"`
	TargetID string `json:"target_id,omitempty"`
	Active   bool   `json:"active,omitempty"`
}

TabInfo holds metadata about a browser tab.

func ListTabs

func ListTabs(browser *rod.Browser, currentTargetID string) ([]TabInfo, error)

ListTabs returns info for every open tab in the browser.

type VideoChapter

type VideoChapter struct {
	Title       string `json:"title"`
	Description string `json:"description,omitempty"`
	DurationMs  int    `json:"duration_ms,omitempty"`
	AtMs        int64  `json:"at_ms"`
	CreatedAt   string `json:"created_at"`
}

VideoChapter is one requested video chapterker.

type VideoRuntimeOpts

type VideoRuntimeOpts struct {
	ConnectURL string
	TargetID   string
	FramesDir  string
	StatusPath string
}

VideoRuntimeOpts describes the detached recorder process attached to a long-lived Chrome. The process, rather than the short-lived CLI command, owns the Page.screencast subscription.

type VideoRuntimeStatus

type VideoRuntimeStatus struct {
	State     string `json:"state"`
	Frames    int64  `json:"frames_captured"`
	StartedAt string `json:"started_at,omitempty"`
	UpdatedAt string `json:"updated_at,omitempty"`
	StoppedAt string `json:"stopped_at,omitempty"`
	Error     string `json:"error,omitempty"`
}

VideoRuntimeStatus is written atomically so video-start and video-stop can prove the detached recorder's state across CLI processes.

func ReadVideoRuntimeStatus

func ReadVideoRuntimeStatus(path string) (VideoRuntimeStatus, error)

func RequestVideoRuntimeStop

func RequestVideoRuntimeStop(statusPath string, timeout time.Duration) (VideoRuntimeStatus, error)

RequestVideoRuntimeStop asks the detached recorder to finish its current frame, stop CDP screencast, and publish its final count.

func WaitForVideoRuntime

func WaitForVideoRuntime(path, want string, timeout time.Duration) (VideoRuntimeStatus, error)

func (VideoRuntimeStatus) IsStale

func (s VideoRuntimeStatus) IsStale(now time.Time, maxAge time.Duration) bool

IsStale reports whether a recording runtime has stopped publishing its heartbeat. Terminal statuses are handled by callers as recoverable too.

type VideoState

type VideoState struct {
	Active        bool           `json:"active,omitempty"`
	StartedAt     string         `json:"started_at,omitempty"`
	Filename      string         `json:"filename,omitempty"`
	FramesDir     string         `json:"frames_dir,omitempty"`
	RuntimeStatus string         `json:"runtime_status,omitempty"`
	Size          string         `json:"size,omitempty"`
	Auto          bool           `json:"auto,omitempty"`
	Source        string         `json:"source,omitempty"`
	Chapters      []VideoChapter `json:"chapters,omitempty"`
}

VideoState tracks a durable CDP screencast recording. The artifact is a sequence of JPEG frames, never a WebM file.

type WaitSpec

type WaitSpec struct {
	Selector string
	Ref      string
	Text     string
	URL      string
	Load     string
	State    string
	MS       int
	Timeout  time.Duration
}

WaitSpec is the JSONL/MCP wait contract. Conditions run in this order: load/url/text/target, then a fixed delay. Empty spec is a no-op.

Jump to

Keyboard shortcuts

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