How to Wait for Agent Control in ego-lite: A Complete Guide

Use taskSpaces.waitForAgentControl() to block execution until the agent regains exclusive control of a task space, with configurable polling intervals and automatic timeout handling.

Waiting for agent control is essential when working with isolated browsing contexts in the citrolabs/ego-lite repository. The waitForAgentControl helper provides a robust mechanism to detect when a task space transitions from user control back to agent control. This guide explains how to implement agent control detection using the internal polling system and handle edge cases effectively.

Understanding Task Space Control in ego-lite

In ego-lite, a task space represents an isolated browsing context that can be owned by either the agent or a user. Certain operations, such as taking over a task space, require exclusive agent control. When a user currently holds control, the agent must wait before executing privileged operations.

The waitForAgentControl function, located in src/helpers.ts (lines 84-108), solves this by continuously probing the task space until control is regained or a timeout occurs.

Using waitForAgentControl

The waitForAgentControl method is exposed through the taskSpaces façade in src/index.ts (line 795), making it accessible as a top-level utility for your automation scripts.

Basic Syntax

Call waitForAgentControl with a task space identifier and optional configuration:

await taskSpaces.waitForAgentControl('my-task-space');

The function accepts either a string name or numeric ID as the first parameter. It returns a Promise that resolves when agent control is confirmed or rejects if the timeout expires.

Configuration Options

Customize the polling behavior using the options object:

  • interval (number): Seconds between control checks. Defaults to 20 seconds.
  • timeout (number): Maximum seconds to wait before throwing an error. Defaults to 600 seconds (10 minutes).
await taskSpaces.waitForAgentControl(42, {
  interval: 5,   // Check every 5 seconds
  timeout: 120,  // Fail after 2 minutes
});

How waitForAgentControl Works Internally

Understanding the implementation helps you debug control detection issues and optimize polling strategies.

Input Validation and Task Space Selection

Before polling begins, the function validates the input parameter to ensure a valid task-space name or numeric ID is supplied. It then selects the target task space (if not already active) via the internal selectTaskSpaceIfProvided helper. This ensures the subsequent probe operations target the correct browsing context.

The Polling Mechanism with probeAgentControl

The core detection logic resides in probeAgentControl (src/helpers.ts, lines 64-73). This helper performs a minimal ego.snapshot request to test control status:

  • Success: If the snapshot succeeds, the agent holds control and waitForAgentControl returns immediately.
  • User Control Detected: If the snapshot throws a user-control error (identified by isEgoUserControlError), the probe returns false and the loop continues.
  • Unexpected Errors: Any other error propagates immediately to prevent endless waiting on system failures.

The function uses waitForTimeout from src/driver/waits.ts to pause between probes according to your specified interval.

Error Handling and Timeout Logic

If the timeout duration elapses without regaining control, the function throws a clear error describing the failure. This allows your code to catch the exception and implement fallback logic, such as notifying operators or aborting the workflow.

Code Examples

Basic Usage with Default Settings

Wait for control using the default 20-second polling interval and 600-second timeout:

// Wait with defaults (20s interval, 600s timeout)
await taskSpaces.waitForAgentControl('my-task-space');
console.log('Agent has control - proceeding with automation');

Custom Polling Intervals and Timeouts

For time-sensitive operations, reduce the interval to check more frequently:

// Aggressive polling for quick control detection
await taskSpaces.waitForAgentControl('checkout-flow', {
  interval: 2,   // Check every 2 seconds
  timeout: 60    // Maximum 1 minute wait
});

Handling Timeout Errors

Always wrap control waits in try-catch blocks to handle timeout scenarios gracefully:

try {
  await taskSpaces.waitForAgentControl('my-task-space', {
    timeout: 30,  // 30 second limit
  });
  console.log('Agent now has control – continuing work');
} catch (err) {
  console.error('Failed to regain control:', err.message);
  // Implement fallback logic here
}

Summary

  • Location: waitForAgentControl is implemented in src/helpers.ts (lines 84-108) and exported through taskSpaces in src/index.ts.
  • Mechanism: Polls by attempting ego.snapshot requests, detecting user-control errors via isEgoUserControlError.
  • Defaults: 20-second polling intervals with a 600-second timeout.
  • Safety: Unexpected errors propagate immediately rather than causing infinite loops.
  • Testing: Reference src/helpers.test.mjs for verified behavior patterns.

Frequently Asked Questions

How does ego-lite determine if a user or agent controls a task space?

The system attempts a minimal ego.snapshot request via the probeAgentControl helper. If the request succeeds, the agent has control. If it throws a user-control error (detected by isEgoUserControlError), a user currently holds control and the agent must wait.

Can I adjust how frequently the agent checks for control?

Yes. Pass an interval option (in seconds) to waitForAgentControl. The default is 20 seconds, but you can set values as low as 1 second for rapid detection or higher values to reduce system load.

What happens if the agent never regains control?

When the specified timeout duration expires (default 600 seconds), the function throws an error describing the timeout. Your code should catch this exception to handle the failure case, such as logging the issue or aborting the operation.

Is waitForAgentControl safe to use in production automation?

Yes. The implementation includes safeguards against infinite loops: it propagates unexpected errors immediately (only user-control errors trigger continued polling), uses configurable timeouts, and relies on the robust waitForTimeout utility from src/driver/waits.ts. The test suite in src/helpers.test.mjs verifies these safety mechanisms.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →