# How to Use `useOrCreateTaskSpace` and `claimTaskSpace` in ego-lite

> Master ego-lite's useOrCreateTaskSpace and claimTaskSpace. Learn to efficiently manage and claim task spaces for agent actions, improving your workflow. Get started today.

- Repository: [CitroLabs/ego-lite](https://github.com/citrolabs/ego-lite)
- Tags: how-to-guide
- Published: 2026-08-28

---

**`useOrCreateTaskSpace` returns an existing agent-owned task space or creates a new one, while `claimTaskSpace` transfers ownership of a user-owned space to the agent so you can perform actions on it.**

Both helpers manage **task spaces** — isolated browsing contexts in `ego-lite` that track navigation history, cookies, and page state. Understanding when to use each helper ensures your automation scripts handle shared browser sessions cleanly without permission errors.

## What Are Task Spaces in ego-lite?

A **task space** is a dedicated browser context identified by either a string name or a numeric ID. Each space has an **ownership** flag: `agent` (controlled by your script) or `user` (controlled by the runtime or previous scripts). The `ego-lite` runtime enforces ownership rules strictly — you cannot modify a user-owned space until you claim it.

These helpers live in [`package/ego-browser/src/helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/helpers.ts) and are exported from [`package/ego-browser/src/index.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/index.ts) for direct use in your scripts.

## `useOrCreateTaskSpace`: Reuse or Initialize Agent-Owned Spaces

The `useOrCreateTaskSpace` function solves the "get or create" pattern for task spaces you control.

### How It Works

Per the implementation in [[`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#L193):

1. Calls `ego.getTaskSpace(nameOrId)` to locate the space
2. If found and owned by `agent`, selects it via `selectTaskSpace`
3. If not found, creates a new agent-owned space with that name
4. Throws an error if the space exists but is user-owned (ownership mismatch)

### Function Signature

```typescript
async function useOrCreateTaskSpace(
  nameOrId: string | number
): Promise<TaskSpace>

```

### Code Example: Persistent Shopping Session

```typescript
// Get or create a task space for checkout flow
const checkoutSpace = await useOrCreateTaskSpace('checkout-session');

// Space is now selected — navigate and interact
await nav('https://shop.example.com/cart');
await click('button=Proceed to Checkout');
await fill('input[id="email"]', 'customer@example.com');

// Later in the same script or a subsequent run,
// the same call returns the existing space with state intact
const sameSpace = await useOrCreateTaskSpace('checkout-session');
// Cart items and form data persist

```

### When to Use It

- Starting a multi-step workflow that may resume later
- Ensuring idempotent script execution (same result on rerun)
- Avoiding "space already exists" or "space not found" errors

## `claimTaskSpace`: Take Control of User-Owned Spaces

The `claimTaskSpace` function transfers ownership from `user` to `agent`, enabling full control over spaces created outside your script.

### How It Works

From [[`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):

1. Locates the space via `ego.getTaskSpace(nameOrId)`
2. Validates current ownership is `user`
3. Transfers ownership to `agent` through the runtime
4. Selects the space for subsequent operations

Ownership transfer is irreversible in the current session — once claimed, the space behaves like any agent-owned space.

### Function Signature

```typescript
async function claimTaskSpace(
  nameOrId: string | number
): Promise<TaskSpace>

```

### Code Example: Resuming a Human-Initiated Session

```typescript
// User manually created space ID 7 through a dashboard
// Your automation now needs to continue that workflow
const handoffSpace = await claimTaskSpace(7);

// Full control granted — proceed with automated actions
await nav('https://app.example.com/onboarding/step-2');
await uploadFile('input[type="file"]', './documents.pdf');
await click('button=Submit Application');

```

### Error Handling

Attempting to claim an already agent-owned space throws:

```

claimTaskSpace cannot claim task space 7 with ownership "agent"

```

Similarly, `useOrCreateTaskSpace` fails on user-owned spaces:

```

useOrCreateTaskSpace cannot use task space "checkout-session" with ownership "user"

```

## Comparing the Two Helpers

| Aspect | `useOrCreateTaskSpace` | `claimTaskSpace` |
|--------|------------------------|------------------|
| **Input space state** | Does not exist, or owned by `agent` | Must exist and be owned by `user` |
| **Output space state** | Agent-owned, selected | Agent-owned, selected |
| **Creates new space?** | Yes, if missing | No — space must exist |
| **Ownership transfer?** | No | Yes (`user` → `agent`) |
| **Typical use case** | Idempotent automation startup | Handoff from manual/external process |

## Complete Workflow Example

This pattern combines both helpers for a robust multi-script pipeline:

```typescript
// === Script 1: Initialization ===
// Create or reuse a space for data collection
const collector = await useOrCreateTaskSpace('data-collector');
await nav('https://source.example.com/data');
const rawData = await extract('table.dataset');
await saveToStore('rawData', rawData);

// Mark space for handoff by converting to user ownership
// (via runtime-specific mechanism, e.g., space.release())

// === Script 2: Processing (runs later, possibly different process) ===
// Claim the space to continue with transformed data
const processor = await claimTaskSpace('data-collector');
const enriched = await transform(rawData);
await nav('https://target.example.com/upload');
await fill('textarea', JSON.stringify(enriched));
await click('button=Publish');

```

## Summary

- **`useOrCreateTaskSpace`** — Safely obtain an agent-owned task space, creating it if necessary. Fails on user-owned spaces to prevent accidental interference.

- **`claimTaskSpace`** — Explicitly take ownership of a user-owned space, enabling full automation control over externally created contexts.

- Both helpers call `selectTaskSpace` internally, ensuring the returned space is active for immediate use.

- Check ownership status before calling either helper to handle expected error cases gracefully.

## Frequently Asked Questions

### What happens if I call `useOrCreateTaskSpace` on a user-owned space?

The function throws an ownership mismatch error. You must first call `claimTaskSpace` to transfer ownership from `user` to `agent`, then proceed with agent operations.

### Can I unclaim a space and return it to user ownership?

The current `ego-lite` implementation in [`src/helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/helpers.ts) does not expose an unclaim mechanism. Once claimed, the space remains agent-owned for the session duration. Restart the runtime to reset ownership states.

### How do I check a space's ownership before calling these helpers?

Use the underlying `ego.getTaskSpace(nameOrId)` method, which returns a space object with an `ownership` property (`"agent"` or `"user"`). Wrap your logic based on this value:

```typescript
const space = await ego.getTaskSpace('my-space');
if (space.ownership === 'user') {
  await claimTaskSpace('my-space');
} else {
  await selectTaskSpace('my-space');
}

```

### Are task space names globally unique or scoped per script?

Task space names are **globally unique** within the `ego-lite` runtime instance. Multiple scripts accessing the same name reference the same browsing context, making ownership management critical for concurrent workflows.