# Browser Facade in ego-lite: Functions, API Reference, and Usage Guide

> Explore the browser facade in ego-lite. Control embedded browsers with a simple JavaScript API for CDP operations, element interaction, network requests, and more. Learn usage and API reference.

- Repository: [CitroLabs/ego-lite](https://github.com/citrolabs/ego-lite)
- Tags: api-reference
- Published: 2026-07-31

---

**The browser facade in ego-lite exposes a high-level JavaScript API through `globalThis.ego.helpers` that wraps Chrome DevTools Protocol (CDP) operations, task-space management, element interaction, file uploads, network requests, and site-specific skill execution, allowing agents to control the embedded browser via simple async functions defined in [`package/ego-browser/src/helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/helpers.ts).**

The browser facade serves as the primary interface between AI agents and the embedded Chromium instance in citrolabs/ego-lite. Located in [`package/ego-browser/src/helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/helpers.ts), this facade abstracts low-level CDP complexity into ergonomic helper functions that agents invoke to manipulate web pages, manage isolated browsing contexts, and execute site-specific automation scripts.

## Core Runtime and CDP Operations

At the foundation of the browser facade are utilities for direct browser communication and script execution. These functions in [`package/ego-browser/src/helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/helpers.ts) delegate to [`cdp-eval.ts`](https://github.com/citrolabs/ego-lite/blob/main/cdp-eval.ts) and [`browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/browser-runtime.ts) to handle the underlying transport layer.

- **`cdp`**: Sends raw Chrome DevTools Protocol messages to the browser instance, providing low-level access when higher-level helpers are insufficient.
- **`evaluate`**: Executes JavaScript expressions directly in the page context and returns serializable results.

These methods enable agents to inspect DOM state, modify page behavior, or access browser internals that lack dedicated facade methods.

## Task-Space Management Functions

The facade provides comprehensive task-space management for isolating browsing sessions. Task spaces represent independent browser contexts that agents can create, switch between, claim, and transfer.

### Creating and Switching Contexts

- **`newTaskSpace(name)`**: Creates a fresh isolated browsing context with the specified identifier.
- **`switchTaskSpace(name)`**: Activates an existing task space, moving the agent’s context to that session.
- **`useOrCreateTaskSpace(name)`**: Idempotently ensures a task space exists, creating it only if absent, then switching to it.
- **`listTaskSpaces()`**: Returns an array of available task spaces and their current states.

### Lifecycle and Ownership

- **`claimTaskSpace(name)`**: Takes ownership of a task space, preventing other agents from interfering.
- **`completeTaskSpace(name)`**: Marks a task space as finished and ready for cleanup.
- **`handOffTaskSpace(name, targetAgent)`**: Transfers ownership of a task space to another agent.
- **`takeOverTaskSpace(name)`**: Assumes control of a task space from another agent.
- **`waitForAgentControl()`**: Pauses execution until the agent has exclusive control over the current task space.

These functions are implemented in [`helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/helpers.ts) and coordinate with [`browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/browser-runtime.ts) to manage CDP session lifecycle and event buffering across contexts.

## Navigation and Element Interaction

While the raw facade exports focus on high-level operations, the browser facade implicitly exposes navigation and interaction capabilities through injected driver modules. Agents access these via the same `globalThis.ego.helpers` object:

- **`nav(url)`**: Navigates the current task space to the specified URL.
- **`click(selector)`**: Resolves the element and performs a click action.
- **`type(selector, text)`**: Inputs text into form fields.
- **`scroll(selector, options)`**: Scrolls elements into view or by offset.
- **`drag(from, to)`**: Performs drag-and-drop operations.

These methods utilize [`element-resolver.ts`](https://github.com/citrolabs/ego-lite/blob/main/element-resolver.ts) to handle complex locator strategies including CSS selectors, XPath, ARIA roles, and indexed references (e.g., `@N` notation), while classifying resolution errors for better agent feedback.

## File Handling and Media Capture

The facade includes dedicated helpers for file uploads and video recording, wrapping CDP commands for media streams.

- **`setInputFiles(selector, filePaths)`**: Uploads local files to `<input type="file">` elements by path.
- **`startScreencast(options)`**: Begins recording the browser viewport to a specified path, typically with MP4 output.
- **`stopScreencast()`**: Finalizes and saves the video recording.

These functions reside in the driver layer (`driver/*`) but are surfaced through the facade’s helper context.

## Network Operations

Agents can perform HTTP requests from either the browser or server context:

- **`browserFetch(url, options)`**: Executes fetch requests from the browser’s JavaScript context, respecting cookies and authentication state.
- **`serverFetch(url, options)`**: Performs requests from the Node.js server environment, bypassing CORS restrictions but lacking session cookies.

## Site-Skill Utilities

The browser facade integrates ego-lite’s learning system for reusable site-specific automation patterns stored under `skills/ego-browser/learnings`.

- **`siteSkillsForUrl(url)`**: Discovers available skills for a given domain.
- **`siteSkills(domain)`**: Lists all registered skills for a specific site.
- **`runSiteTool(domain, toolName, params)`**: Executes a predefined tool against the current page.
- **`runSiteBrowserTool(domain, toolName, params)`**: Runs tools specifically designed for browser interaction.
- **`learnContext(context)`**: Captures current page state for skill learning and validation.

These utilities delegate to the `learning/*` folder implementations, allowing agents to leverage pre-trained workflows for common sites like GitHub or internal applications.

## Implementation Architecture

The facade is constructed dynamically via **`helperContext()`** and injected into agent scripts through **`loadAgentHelpers()`**. This architecture separates the public API from underlying implementations:

- **[`browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/browser-runtime.ts)**: Manages CDP transport, session lifecycle, and event buffering.
- **[`element-resolver.ts`](https://github.com/citrolabs/ego-lite/blob/main/element-resolver.ts)**: Handles selector resolution and error classification.
- **[`cdp-eval.ts`](https://github.com/citrolabs/ego-lite/blob/main/cdp-eval.ts)**: Implements raw CDP messaging and JavaScript evaluation.
- **`driver/*`**: Contains concrete implementations for pointer, keyboard, file, and screencast operations.
- **[`learning/index.ts`](https://github.com/citrolabs/ego-lite/blob/main/learning/index.ts)**: Provides site-skill discovery and execution logic.

For testing, the facade exposes **`__testing.setOverrides()`** and **`__testing.decodeUnserializableJsValue()`** to mock browser state and handle special value types during unit tests.

## Code Examples

Create a new task space and navigate to a page:

```javascript
const { newTaskSpace, switchTaskSpace, nav } = globalThis.ego.helpers;

await newTaskSpace('my-space');
await switchTaskSpace('my-space');
await nav('https://example.com');

```

Upload a file and submit a form:

```javascript
const { setInputFiles, click } = globalThis.ego.helpers;

await setInputFiles('#file-input', ['/path/to/file.png']);
await click('#submit-btn');

```

Execute a site-specific skill:

```javascript
const { runSiteTool } = globalThis.ego.helpers;

const result = await runSiteTool('github', 'searchRepositories', { query: 'ego-lite' });
console.log(result);

```

Record a screencast session:

```javascript
const { startScreencast, stopScreencast, snapshot } = globalThis.ego.helpers;

await startScreencast({ path: '/tmp/record.mp4' });
await snapshot();  // Capture screenshot during recording
await stopScreencast();

```

## Summary

- The browser facade in [`package/ego-browser/src/helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/helpers.ts) provides the primary API surface for agents to control Chromium via `globalThis.ego.helpers`.
- **Task-space functions** (`newTaskSpace`, `switchTaskSpace`, `claimTaskSpace`, etc.) manage isolated browsing contexts and ownership transfers.
- **CDP wrappers** (`cdp`, `evaluate`) offer low-level browser access when needed.
- **File and media helpers** (`setInputFiles`, `startScreencast`) handle uploads and video recording.
- **Site-skill utilities** (`runSiteTool`, `siteSkillsForUrl`) enable reusable automation patterns for specific domains.
- The facade abstracts [`browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/browser-runtime.ts), [`element-resolver.ts`](https://github.com/citrolabs/ego-lite/blob/main/element-resolver.ts), and driver modules into a stable, async-friendly interface.

## Frequently Asked Questions

### What is the difference between `browserFetch` and `serverFetch` in the ego-lite browser facade?

`browserFetch` executes requests from within the browser’s JavaScript context, maintaining session cookies, authentication headers, and CORS restrictions, making it ideal for interacting with authenticated APIs. `serverFetch` runs from the Node.js server environment, bypassing CORS but lacking access to the browser’s cookie jar or session storage.

### How does task-space isolation work in ego-lite?

Task spaces create isolated browser contexts that prevent cross-contamination between agent workflows. When you call `newTaskSpace`, the facade initializes a fresh CDP session with separate cookies, localStorage, and execution contexts. The `switchTaskSpace` function activates a specific context, while `claimTaskSpace` and `handOffTaskSpace` manage ownership transitions between multiple agents or workflow stages.

### Where are site skills stored and how does the facade access them?

Site skills are bundled under `skills/ego-browser/learnings` in the repository. The facade exposes `siteSkillsForUrl` and `runSiteTool` functions that interface with the learning layer in [`package/ego-browser/src/learning/index.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/learning/index.ts). These utilities validate skill manifests, match them against current URLs, and execute predefined automation scripts for specific domains like GitHub or custom internal applications.

### Can I use the browser facade to record video of automation sessions?

Yes. The facade provides `startScreencast` and `stopScreencast` functions that wrap CDP screencast events. Call `startScreencast({ path: '/output/video.mp4' })` before your automation sequence, then `stopScreencast()` when complete. You can also capture individual screenshots during recording using the `snapshot` helper, which is useful for debugging specific steps while maintaining continuous video capture.