> ## Documentation Index
> Fetch the complete documentation index at: https://docs.webrun.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Sessions

> Understanding browser sessions and their lifecycle

A session is an isolated browser instance running your automation tasks. You get a dedicated environment with a unique `sessionId` that persists until you terminate it or it times out due to inactivity (sessions expire after 5 minutes of inactivity).

Sessions run completely isolated—no shared cookies, no shared state. This lets you run multiple concurrent sessions without interference. Run tasks sequentially within the same session: navigate to a site, authenticate, then execute your workflow. Terminate when done, or you'll pay for the full timeout window.

***

## Session Lifecycle

Sessions progress through these states:

**Pending** → Browser instance initializing
**Active** → Task currently executing
**Completed** → Session ended successfully
**Terminated** → Ended by user or timeout
**Failed** → Session ended due to error
**Orphaned** → Instance disconnected unexpectedly (reconnection window available)

Orphaned sessions are rare. If a browser instance loses connection, the session waits for reconnection. If it doesn't reconnect within the grace period, the session fails.

***

## Configuration Parameters

Configure sessions when creating them:

```javascript theme={null}
{
  "environmentId": "683a1f2e4b0c1d2e3f4a5b6c",     // Optional: reuse browser profile & files
  "policyId": "pol_xyz789",                          // Optional: enforce automation rules
  "proxy": { "source": "WebRun", "country": "US" }, // Optional: route through proxy
  "reachOutMode": "guardrail_only",                  // Optional: chat-user reach-out mode ("off" | "guardrail_only" | "full")
  "mode": "default",                              // Session mode
  "task": {
    "prompt": "What to do",                  // Initial task (can be empty)
    "startingUrl": "https://example.com",       // Skip navigation
    "maxDuration": 300000,                        // Task timeout in ms (max 5 min)
    "maxInputTokens": 100000,                     // AI model input limit
    "maxOutputTokens": 100000,                    // AI model output limit
    "terminateOnCompletion": false,               // Auto-terminate after first task
    "secrets": [                                   // Credentials for website auth
      { "match": "*.example.com", "fields": { "email": "user@co.com", "password": "pass" } }
    ],
    "outputType": "structured_json",              // "text", "structured_json", or "structured_csv"
    "outputSchema": { ... }                       // JSON Schema for structured output
  }
}
```

**Key parameters:**

* **mode**: Session mode (currently only `"default"` is supported).
* **task**: Contains all task-specific parameters.
* **prompt**: Can be empty if you plan to send tasks later via `/send-message`.
* **startingUrl**: Saves tokens and time by skipping navigation.
* **maxDuration**: Maximum time a task can run before automatic termination (default: 5 minutes). Note: Session inactivity timeout is fixed at 5 minutes.
* **terminateOnCompletion**: Automatically `true` for `/start/run-task` endpoint.
* **policyId**: Attach an [automation policy](/concepts/policies) to enforce runtime rules on agent actions. Policies cover domain restrictions, action rules, URL patterns, and sensitive data. This is a top-level parameter, not nested inside `task`.
* **secrets**: Provide credentials upfront so the agent can authenticate without guardrail interruptions. Secrets are never stored and are discarded when the session ends. See [Secrets guide](/usage-guides/secrets).
* **environmentId**: Attach an [environment](/environments/overview) to reuse saved cookies, local storage, files, and other browser data. This is a top-level parameter, not nested inside `task`.
* **proxy**: Route the session through a proxy server for geographic targeting or IP management. Use WebRun-managed proxies or bring your own. Adds 2-3 seconds of cold-start latency. See [Proxies guide](/usage-guides/proxies).
* **reachOutMode**: Controls proactive chat messages to a user (Telegram, WhatsApp, Slack, Discord, Teams) connected to the same [environment](/environments/overview), only when no client is actively watching the session. One of `"off"` (no messages), `"guardrail_only"` (default — bot pings on guardrails like CAPTCHA/2FA/login), or `"full"` (also delivers task results to chat on completion). Use `"off"` for sessions handling private data you don't want surfaced through chat. See [Handling Guardrails](/usage-guides/handling-guardrails#routing-guardrails-to-a-chat-user).

***

## Session Types

### Persistent Session

Create a session that stays open for multiple tasks:

```bash theme={null}
POST /start/start-session
```

Use persistent sessions when you need to execute multiple related tasks or when tasks depend on previous state (like staying logged in).

### Single-Task Session

Create a session that auto-terminates after one task:

```bash theme={null}
POST /start/run-task
```

Use single-task sessions for one-off automations with no follow-up actions. This is the simplest integration pattern.

***

## Key Behaviors

**One task at a time:**
Sessions execute tasks sequentially, not in parallel. If you send a new task while one is running, it queues and starts after the current task completes.

**Inactivity timeout:**
Sessions automatically terminate after 5 minutes of inactivity. Active sessions can run indefinitely. You're billed only for actual compute time used.

**Complete isolation:**
No shared cookies, cache, or session state between sessions. Each session starts with a clean browser — unless an [environment](/environments/overview) is attached. Environments let you persist cookies, local storage, files, and other browser data across sessions.

**Billing:**
Sessions are billable from creation until termination or timeout. Idle time between tasks counts as compute time. Always terminate sessions when finished.

***

## Common Patterns

**Pattern 1: Single task**

```javascript theme={null}
// Create and auto-terminate
POST /start/run-task
{
  "prompt": "Extract data from this page"
}
```

**Pattern 2: Multi-task sequence**

```javascript theme={null}
// Create session
POST /start/start-session
{ "prompt": "Navigate to site" }

// Send follow-up task
POST /start/send-message
{
  "sessionId": "sess_abc",
  "message": {
    "actionType": "newTask",
    "prompt": "Extract data"
  }
}

// Terminate explicitly
POST /start/send-message
{
  "sessionId": "sess_abc",
  "message": { "actionType": "state", "newState": "terminate" }
}
```

**Pattern 3: Multi-task with auto-terminate**

```javascript theme={null}
// Create session
POST /start/start-session
{ "prompt": "Navigate to site" }

// Final task with auto-terminate
POST /start/send-message
{
  "sessionId": "sess_abc",
  "message": {
    "actionType": "newTask",
    "prompt": "Extract data",
    "terminateOnCompletion": true  // Auto-terminates after this task
  }
}
```

***

<CardGroup cols={2}>
  <Card title="Session Control" icon="gamepad" href="/usage-guides/controlling-sessions">
    Pause, resume, stop, and terminate sessions
  </Card>

  <Card title="Tasks" icon="check" href="/concepts/tasks">
    Understanding task lifecycle and execution
  </Card>

  <Card title="Multi-Task Workflows" icon="list-check" href="/usage-guides/multi-task-workflows">
    Chain tasks effectively
  </Card>

  <Card title="Cost Optimization" icon="piggy-bank" href="/usage-guides/cost-optimization">
    Reduce costs with session management
  </Card>

  <Card title="Environments" icon="box" href="/environments/overview">
    Persist browser data and files across sessions
  </Card>

  <Card title="Proxies" icon="globe" href="/usage-guides/proxies">
    Route sessions through proxy servers
  </Card>

  <Card title="Automation Policies" icon="shield-check" href="/concepts/policies">
    Runtime rules that control agent behavior
  </Card>
</CardGroup>
