# Task Space Lifecycle in ego-lite: From Creation to Completion

> Explore the ego-lite task space lifecycle from creation to completion. Understand the eight distinct stages and how async helpers manage each step in the process.

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

---

**The lifecycle of a task space in ego-lite progresses through eight distinct stages—creation, discovery, claiming, switching, handoff, takeover, completion, and listing—each controlled by specific async helpers exported from [`src/helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/helpers.ts).**

The **ego-lite** framework (`citrolabs/ego-lite`) isolates browser automation into discrete **task spaces** that maintain independent cookies, storage, and page state. Understanding the complete lifecycle of a task space—from initial creation through user handoffs to final teardown—is essential for building robust scripts that manage multiple concurrent browsing contexts without conflicts.

## What Is a Task Space in ego-lite?

A **task space** represents an isolated browsing context within the ego-lite runtime. Each space carries a unique `taskId` and can exist in one of two ownership states: **agent-owned** (controlled by your automation script) or **user-owned** (controlled by the human user). Ownership determines which operations are permitted; for example, an agent cannot directly switch to a user-owned space without first claiming it.

## Task Space Lifecycle Stages

### 1. Creation with newTaskSpace

The lifecycle begins with `newTaskSpace(name)`, which instantiates an **agent-owned** space and immediately selects it for the current Node invocation. As implemented in [[`helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/helpers.ts)](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/helpers.ts) at lines 171-184, this function calls the underlying driver to initialize the context.

```javascript
import { newTaskSpace } from 'ego-lite';

// Create a new agent-owned space named 'checkout-flow'
const space = await newTaskSpace('checkout-flow');
console.log(space.taskId); // Numeric ID for this session

```

### 2. Discovery and Reuse with useOrCreateTaskSpace

Rather than spawning duplicates, scripts should call `useOrCreateTaskSpace(nameOrId)` (lines 193-215). This helper locates an existing space by name or ID:
- If **agent-owned**, it selects the space immediately.
- If **user-owned**, it selects the space without transferring ownership (the user retains control).
- If no match exists, it delegates to `newTaskSpace` to create one.

```javascript
import { useOrCreateTaskSpace } from 'ego-lite';

// Reuse 'inventory-check' or create if absent
const space = await useOrCreateTaskSpace('inventory-check');

```

### 3. Claiming Ownership with claimTaskSpace

To convert a **user-owned** space to **agent-owned**, invoke `claimTaskSpace(nameOrId)` at lines 224-227. Claiming is required before performing automated actions on spaces that were created or previously handed off to the user.

```javascript
import { claimTaskSpace } from 'ego-lite';

// Take control of a user-created space
await claimTaskSpace('user-dashboard-123');

```

### 4. Switching Contexts with switchTaskSpace

The `switchTaskSpace(nameOrId)` function (lines 152-164) moves the agent’s focus to another **agent-owned** space. It validates ownership and throws if the target is user-owned, enforcing the security boundary between agent and user contexts.

```javascript
import { switchTaskSpace } from 'ego-lite';

// Switch to space by numeric ID
await switchTaskSpace(42);

// Or switch by string name
await switchTaskSpace('secondary-cart');

```

### 5. Handing Off Control with handOffTaskSpace

To return a space to the user, call `handOffTaskSpace([nameOrId])` (lines 326-340). This marks the space as **user-owned**, hides the agent overlay, and allows manual interaction. If the space is already user-owned, the call is effectively a no-op.

```javascript
import { handOffTaskSpace } from 'ego-lite';

// Return current space to user for payment review
await handOffTaskSpace();

// Or hand off a specific space by name
await handOffTaskSpace('payment-confirmation');

```

### 6. Resuming Control with takeOverTaskSpace

When the agent needs to resume work, `takeOverTaskSpace([nameOrId])` (lines 347-354) converts the space back to **agent-owned** and restores the automation overlay.

```javascript
import { takeOverTaskSpace } from 'ego-lite';

// Resume automation after user interaction
await takeOverTaskSpace('payment-confirmation');

```

### 7. Completion and Teardown with completeTaskSpace

The terminal stage is handled by `completeTaskSpace(nameOrId, {keep})` (lines 274-317). This function finalizes the session:
- When `keep: true`, it dismisses the agent overlay but leaves the browser page open for the user.
- When `keep: false`, it claims the space if necessary and then closes it entirely, cleaning up resources.

```javascript
import { completeTaskSpace } from 'ego-lite';

// Close space and cleanup
await completeTaskSpace('checkout-flow', { keep: false });

// Or keep open for user inspection
await completeTaskSpace('generated-report', { keep: true });

```

### 8. Listing and Discovery Utilities

The helper `listTaskSpaces()` queries the runtime for all known spaces, returning metadata including `taskId`, `name`, and `ownership`. Internal utilities such as `findTaskSpace` and `findMatchingTaskSpace` (located in [`helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/helpers.ts)) support lookup by exact name or numeric ID.

```javascript
import { listTaskSpaces } from 'ego-lite';

const allSpaces = await listTaskSpaces();
// Returns array: [{ taskId, name, ownership: 'agent' | 'user' }, ...]

```

## Complete Code Example: A Full Workflow

The following example demonstrates a realistic lifecycle: creating a space, performing work, handing off to a user, reclaiming control, and completing the task.

```javascript
import { 
  newTaskSpace, 
  useOrCreateTaskSpace,
  claimTaskSpace,
  switchTaskSpace,
  handOffTaskSpace,
  takeOverTaskSpace,
  completeTaskSpace,
  listTaskSpaces 
} from 'ego-lite';

async function processOrder(orderId) {
  // Stage 1: Create dedicated agent-owned space
  const space = await newTaskSpace(`order-${orderId}`);
  console.log(`Created space ${space.name} with ID ${space.taskId}`);
  
  // ... perform automation steps ...
  
  // Stage 2: Hand off to user for manual payment entry
  await handOffTaskSpace(space.name);
  
  // Stage 3: Agent resumes control when user signals completion
  await takeOverTaskSpace(space.name);
  
  // Stage 4: Finalize and close the space
  const result = await completeTaskSpace(space.name, { keep: false });
  console.log('Space closed:', result.done);
  
  // Verify removal
  const remaining = await listTaskSpaces();
  const active = remaining.find(s => s.name === `order-${orderId}`);
  console.log('Space still exists:', !!active);
}

processOrder('12345');

```

## Key Source Files

- **[[`src/helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/helpers.ts)](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/helpers.ts)**: Implements the public lifecycle API including `newTaskSpace`, `useOrCreateTaskSpace`, `claimTaskSpace`, `switchTaskSpace`, `handOffTaskSpace`, `takeOverTaskSpace`, and `completeTaskSpace`.

- **[[`src/index.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/index.ts)](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/index.ts)**: Exports the helper surface to consumer scripts and defines the package’s public interface.

- **[[`src/state.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/state.ts)](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/state.ts)**: Maintains the singleton runtime state, tracking the currently selected task space across asynchronous operations.

- **[`src/driver/*.ts`](https://github.com/citrolabs/ego-lite/tree/main/package/ego-browser/src/driver)**: Contains Chrome DevTools Protocol (CDP) drivers that execute native `ego.*` methods (e.g., `ego.createTaskSpace`, `ego.useTaskSpace`, `ego.closeTaskSpace`).

- **[`src/taskspace-e2e.test.mjs`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/taskspace-e2e.test.mjs)**: End-to-end test suite validating the complete lifecycle from creation through handoff to completion.

## Summary

- **Task spaces** are isolated browsing contexts that can be **agent-owned** or **user-owned**.
- **Creation** via `newTaskSpace` or `useOrCreateTaskSpace` establishes the initial context.
- **Claiming** converts user-owned spaces to agent-owned; **switching** moves focus between agent-owned spaces only.
- **Handoff** (`handOffTaskSpace`) returns control to the user; **takeover** (`takeOverTaskSpace`) reclaims it.
- **Completion** (`completeTaskSpace`) finalizes the lifecycle, optionally preserving the page or closing it entirely.
- All lifecycle helpers reside in [`src/helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/helpers.ts) and operate on the runtime state managed by [`src/state.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/state.ts).

## Frequently Asked Questions

### What is the difference between agent-owned and user-owned task spaces?

An **agent-owned** space is fully controlled by your automation script, allowing unrestricted switching and claiming. A **user-owned** space is under manual user control; the agent can view it but cannot switch to it or modify it without first calling `claimTaskSpace` to transfer ownership.

### Can I switch to a user-owned task space without claiming it?

No. The `switchTaskSpace` function explicitly checks ownership and throws an error if the target is user-owned. This design prevents accidental interference with the user's manual browsing session. You must call `claimTaskSpace` first to convert the space to agent-owned status.

### What happens if I call completeTaskSpace with keep: true?

When `keep: true`, `completeTaskSpace` dismisses the agent overlay and marks the task as finished, but leaves the browser tab and underlying page open for the user. The space transitions to user-owned if it wasn't already, allowing continued human interaction without agent interference.

### How do I list all available task spaces in the current session?

Use the `listTaskSpaces()` helper exported from [`src/helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/helpers.ts). It returns an array of space metadata objects containing `taskId`, `name`, and `ownership` properties, enabling you to discover existing contexts before attempting to create or switch to them.