# Endpoints
Source: https://docs.webrun.ai/api-reference/endpoints
Complete reference for all WebRun API endpoints
## Base URL
```
https://api.webrun.ai
```
All endpoints use this base URL unless otherwise specified.
***
## Session Endpoints
### POST /start/start-session
Create a new persistent session that can run multiple tasks.
**Authentication:** Required
**Request Body:**
```json theme={null}
{
"environmentId": "683a1f2e4b0c1d2e3f4a5b6c",
"policyId": "pol_xyz789",
"proxy": { "source": "WebRun", "country": "US" },
"reachOutMode": "guardrail_only",
"mode": "default",
"task": {
"prompt": "Go to amazon.com and search for laptops",
"startingUrl": "https://amazon.com",
"maxDuration": 300000,
"maxInputTokens": 100000,
"maxOutputTokens": 100000,
"terminateOnCompletion": false,
"outputType": "structured_json",
"outputSchema": {
"type": "object",
"properties": {
"results": { "type": "array" }
}
},
"secrets": [
{
"match": "*.amazon.com",
"fields": { "email": "user@example.com", "password": "pass123" }
}
]
}
}
```
The `task` object contains all task-specific parameters. Use `startingUrl` to specify the URL where the task should begin. Use `environmentId` (top-level) to attach an [environment](/environments/overview) with saved cookies, browser state, and persistent files. Use `policyId` (top-level) to enforce [automation policy](/concepts/policies) rules on agent actions. Use `proxy` (top-level) to route the session through a [proxy server](/usage-guides/proxies).
**Response (200 OK):**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"socketURL": "https://api.webrun.ai",
"streaming": {
"webRTCURL": "https://a1b2c3d4e5f6.webrun.ai/whep",
"webViewURL": "https://a1b2c3d4e5f6.webrun.ai",
"dimensions": { "width": 1024, "height": 600 }
},
"initialPrompt": "Go to amazon.com",
"expiresIn": 300000,
"balance": 12.50,
"message": "Connect to instance using sessionId in auth"
}
```
**Error Responses:**
* `401` - Missing or invalid API key
* `402` - Insufficient balance
* `403` - Account deactivated
* `429` - Rate limit exceeded
* `503` - No available instances
See [Parameters Reference](/api-reference/parameters) for detailed parameter descriptions.
***
### POST /start/send-message
Universal endpoint for all session control commands. Handles tasks, state changes, interactions, and guardrails.
**Authentication:** Required
**Request Body:**
```json theme={null}
{
"sessionId": "a1b2c3d4e5f6",
"message": {
"actionType": "newTask | state | interaction | guardrail",
// ... action-specific fields
}
}
```
**Supported Action Types:**
#### actionType: newTask
Start a new task. Returns taskId for polling.
```json theme={null}
{
"sessionId": "a1b2c3d4e5f6",
"message": {
"actionType": "newTask",
"newState": "start",
"prompt": "Search for laptops",
"startingUrl": "https://amazon.com",
"files": ["abc123..."],
"maxDuration": 60000,
"maxInputTokens": 50000,
"maxOutputTokens": 50000,
"terminateOnCompletion": true,
"outputType": "structured_json",
"outputSchema": {
"type": "object",
"properties": {
"products": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"price": { "type": "number" }
}
}
}
}
}
}
}
```
**Response (completed within 50 seconds):**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"type": "task_completed",
"data": {
"message": "Found 50 laptop results",
"files": [],
"network": [
{
"id": "abc12",
"taskId": "x9y8z7w6v5u4",
"urls": [
{
"url": "https://www.amazon.com/s?k=laptops",
"timestamp": 1771138379087.646
}
]
}
]
},
"usage": {
"prompt_tokens": 8500,
"completion_tokens": 2300,
"total_tokens": 10800,
"completion_time": 18.3,
"cost": 0.0087
}
}
```
**Response (still running):**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"status": "pending",
"pollUrl": "https://api.webrun.ai/task/a1b2c3d4e5f6/x9y8z7w6v5u4"
}
```
#### actionType: state
Control task execution (pause, resume, stop, terminate). Returns immediate success.
```json theme={null}
{
"sessionId": "a1b2c3d4e5f6",
"message": {
"actionType": "state",
"newState": "pause | resume | stop | terminate"
}
}
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Message sent successfully"
}
```
#### actionType: interaction
Manual browser control. Returns immediate success.
```json theme={null}
{
"sessionId": "a1b2c3d4e5f6",
"message": {
"actionType": "interaction",
"action": {
"type": "CLICK | TYPE | KEY_PRESS | takeOverControl | releaseControl",
// ... action-specific parameters
}
}
}
```
**Available Interaction Types:**
* `takeOverControl` - Enable manual mode
* `releaseControl` - Return control to AI
* `CLICK` - Click at coordinates `{x, y}`
* `DOUBLE_CLICK` - Double click at coordinates `{x, y}`
* `TYPE` - Type text `{text, humanLike}`
* `KEY_PRESS` - Press key `{key}`
**Response:**
```json theme={null}
{
"success": true,
"message": "Message sent successfully"
}
```
#### actionType: guardrail
Respond to guardrail trigger. Returns immediate success.
```json theme={null}
{
"sessionId": "a1b2c3d4e5f6",
"message": {
"actionType": "guardrail",
"prompt": "Username: user@example.com, Password: pass123",
"newState": "resume"
}
}
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Message sent successfully"
}
```
**Error Responses:**
* `400` - Missing required fields (sessionId, message)
* `401` - Session not found or unauthorized
***
### POST /start/run-task
Execute a single task with auto-terminating session. Simplified version of start-session + send-message.
**Authentication:** Required
`terminateOnCompletion` is automatically set to `true` for this endpoint. The session will close after task completion.
**Request Body:**
```json theme={null}
{
"task": {
"prompt": "Search Google for Anthropic",
"startingUrl": "https://google.com",
"files": ["abc123..."],
"maxDuration": 300000,
"maxInputTokens": 100000,
"maxOutputTokens": 100000
},
"environmentId": "683a1f2e4b0c1d2e3f4a5b6c",
"policyId": "pol_xyz789",
"proxy": { "source": "WebRun", "country": "US" },
"reachOutMode": "guardrail_only",
"mode": "default"
}
```
**Response (completed within 50 seconds):**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"type": "task_completed",
"data": {
"message": "Successfully searched for Anthropic",
"files": [],
"network": [
{
"id": "tevo9",
"taskId": "x9y8z7w6v5u4",
"urls": [
{
"url": "https://www.google.com/search?q=Anthropic",
"timestamp": 1771138379087.646
}
]
}
]
},
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"completion_time": 23.5,
"cost": 0.0124
}
}
```
**Response (still running):**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"status": "pending",
"pollUrl": "https://api.webrun.ai/task/a1b2c3d4e5f6/x9y8z7w6v5u4",
"message": "Task still running. Poll GET /task/:sessionId/:taskId for result."
}
```
**Error Responses:**
* `400` - Missing task.prompt
* `401` - Missing or invalid API key
* `402` - Insufficient balance
* `503` - No available instances
***
## File Upload Endpoints
### POST /files/upload
Upload one or more files to use in tasks. Returns `fileId` references that can be attached to any task endpoint.
**Authentication:** Required
**Content-Type:** `multipart/form-data`
**Request:**
```bash theme={null}
curl -X POST https://api.webrun.ai/files/upload \
-H "Authorization: Bearer wr_xxx" \
-F "files=@document.pdf"
```
**Response (200 OK):**
```json theme={null}
{
"success": true,
"files": [
{
"fileId": "abc123...",
"originalName": "document.pdf",
"size": 102400
}
]
}
```
Use the returned `fileId` values in the `files` array at the task level: inside `task` for `/start/start-session`, in the request body for `/start/run-task`, or inside `message` for `/start/send-message`.
See [File Uploads guide](/environments/file-uploads) for complete examples.
***
## Task Endpoints
### GET /task/:sessionId/:taskId
Poll for task result.
**Path Parameters:**
* `sessionId` - Session identifier
* `taskId` - Task identifier
**Response (still running):**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"status": "running",
"usage": {
"prompt_tokens": 8000,
"completion_tokens": 2100,
"total_tokens": 10100,
"completion_time": 12.3,
"cost": 0.0067
}
}
```
**Response (completed):**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"type": "task_completed",
"data": {
"message": "Task finished successfully",
"files": [
{
"source": "https://example.com/report.zip",
"downloadUrl": "https://blobs.webrun.ai/files/report.zip",
"filename": "report.zip",
"timestamp": 1771138379108
}
],
"network": [
{
"id": "tevo9",
"taskId": "x9y8z7w6v5u4",
"urls": [
{
"url": "https://example.com/api/data",
"timestamp": 1771138379087.646
}
]
}
]
},
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"completion_time": 23.5,
"cost": 0.0124
},
"completedAt": "2024-01-15T10:30:00Z"
}
```
**Response (guardrail triggered):**
```json theme={null}
{
"success": true,
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "I need login credentials to proceed"
}
}
```
**Response (failed):**
```json theme={null}
{
"success": false,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"status": "failed",
"error": "Navigation timeout after 30 seconds",
"code": "NAVIGATION_TIMEOUT",
"usage": {
"prompt_tokens": 5000,
"completion_tokens": 1200,
"total_tokens": 6200,
"completion_time": 30.0,
"cost": 0.0045
}
}
```
**Error Responses:**
* `404` - Task not found
***
## OpenAI-Compatible Endpoints
### POST /v1/chat/completions
OpenAI-compatible chat completions endpoint. Creates a new session for each request and auto-terminates after completion.
**Authentication:** Required (Bearer token)
The OpenAI-compatible endpoint creates a new session for each request. For multi-task workflows, use the native REST API.
**Request Body:**
```json theme={null}
{
"model": "webrun-browser-1",
"messages": [
{
"role": "system",
"content": "You are a helpful browser automation assistant."
},
{
"role": "user",
"content": "Go to example.com and extract all headings"
}
],
"stream": false,
"max_tokens": 2000
}
```
**Response (Non-Streaming):**
```json theme={null}
{
"id": "chatcmpl-a1b2c3d4e5f6",
"object": "chat.completion",
"created": 1704067200,
"model": "webrun-browser-1",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "I found 5 headings on example.com:\n1. Example Domain\n2. More Information\n3. Contact\n4. About\n5. Privacy Policy"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 8450,
"completion_tokens": 2100,
"total_tokens": 10550
},
"webrun": {
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"cost": 0.0089
}
}
```
**Response (Streaming):**
Server-Sent Events (SSE) format:
```
data: {"id":"chatcmpl-a1b2c3","object":"chat.completion.chunk","created":1704067200,"model":"webrun-browser-1","choices":[{"index":0,"delta":{"role":"assistant","content":"I"},"finish_reason":null}]}
data: {"id":"chatcmpl-a1b2c3","object":"chat.completion.chunk","created":1704067200,"model":"webrun-browser-1","choices":[{"index":0,"delta":{"content":" found"},"finish_reason":null}]}
data: {"id":"chatcmpl-a1b2c3","object":"chat.completion.chunk","created":1704067200,"model":"webrun-browser-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
```
**Error Responses:**
* `401` - Invalid API key
* `402` - Insufficient balance
* `429` - Rate limit exceeded
* `503` - No browser instances available
* Guardrail error: `{"error": {"message": "Guardrail triggered: I need login credentials to proceed", "type": "guardrail_error", "code": "guardrail_triggered"}}`
See [OpenAI-Compatible API](/integrations/openai-compatible) for detailed integration guide.
***
### GET /v1/models
List available models for OpenAI-compatible endpoint.
**Authentication:** Required (Bearer token)
**Response:**
```json theme={null}
{
"object": "list",
"data": [
{
"id": "webrun-browser-1",
"object": "model",
"created": 1704067200,
"owned_by": "webrun"
}
]
}
```
***
## Monitoring Endpoints
### GET /start/health
System health check.
**Response:**
```json theme={null}
{
"success": true,
"status": "healthy",
"instancesAvailable": true,
"instanceCount": 5,
"timestamp": "2024-01-15T10:30:00.000Z"
}
```
***
## Endpoint Summary
| Endpoint | Method | Auth | Rate Limit | Description |
| ---------------------------- | ------ | ------------ | ---------------- | ------------------------------ |
| `/start/start-session` | POST | Required | 10/min per user | Create persistent session |
| `/start/send-message` | POST | Required | 10/min per user | Send commands to session |
| `/start/run-task` | POST | Required | 10/min per user | Execute single task |
| `/task/:sessionId/:taskId` | GET | Not required | None | Poll for task result |
| `/v1/chat/completions` | POST | Required | 10/min per user | OpenAI-compatible chat |
| `/v1/models` | GET | Required | None | List available models |
| `/files/upload` | POST | Required | 10/min per user | Upload files for tasks |
| `/start/health` | GET | Not required | None | System health check |
| `/profiles` | GET | Required | 100/15min per IP | List all profiles |
| `/profiles` | POST | Required | 100/15min per IP | Create a profile |
| `/profiles/:id` | DELETE | Required | 100/15min per IP | Delete a profile |
| `/profiles/:id/download` | GET | Required | 100/15min per IP | Download profile data |
| `/profiles/:id/upload` | POST | Required | 100/15min per IP | Upload profile data |
| `/cron-jobs` | GET | Required | — | List all triggers |
| `/cron-jobs` | POST | Required | — | Create a trigger |
| `/cron-jobs/:id` | GET | Required | — | Get a trigger with recent runs |
| `/cron-jobs/:id` | PUT | Required | — | Update a trigger |
| `/cron-jobs/:id` | DELETE | Required | — | Delete a trigger |
| `/cron-jobs/:id/pause` | POST | Required | — | Pause a trigger |
| `/cron-jobs/:id/resume` | POST | Required | — | Resume a paused trigger |
| `/cron-jobs/:id/trigger` | POST | Required | — | Manually run a trigger |
| `/cron-jobs/:id/runs` | GET | Required | — | List trigger run history |
| `/cron-jobs/:id/runs/:runId` | GET | Required | — | Get a specific run |
***
Detailed parameter documentation
Complete response format reference
Schedule recurring tasks with full API reference
# Parameters
Source: https://docs.webrun.ai/api-reference/parameters
Complete reference for all WebRun API parameters
## Session Parameters
Parameters used when creating a new session via `POST /start/start-session`.
### environmentId
* **Type:** `string`
* **Required:** No
* **Default:** `null`
* **Description:** ID of an [environment](/environments/overview) to attach to the session. When set, the browser loads the environment's saved cookies, local storage, extensions, and other browser data before starting the task. Files stored in the environment are also available to the session. This maintains consistent browser state (e.g., login sessions) and persistent file access across multiple sessions.
**Example:**
```json theme={null}
{
"environmentId": "683a1f2e4b0c1d2e3f4a5b6c",
"mode": "default",
"task": {
"prompt": "Go to amazon.com and check my orders"
}
}
```
Use profiles to skip login steps. Log in once with a profile attached, then reuse that profile for future sessions. The saved cookies keep you authenticated.
***
### policyId
* **Type:** `string`
* **Required:** No
* **Default:** `null`
* **Description:** ID of an [automation policy](/concepts/policies) to enforce during the session. When set, every agent action is evaluated against the policy's rules before execution. Actions can be allowed, blocked, or paused for human approval depending on the matching rule. Policies cover domain restrictions, keyword filters, action types, URL patterns, and sensitive data detection.
**Example:**
```json theme={null}
{
"environmentId": "683a1f2e4b0c1d2e3f4a5b6c",
"policyId": "pol_xyz789",
"mode": "default",
"task": {
"prompt": "Extract the latest invoice from the vendor portal",
"startingUrl": "https://vendor.example.com"
}
}
```
`policyId` is a top-level session parameter, alongside `environmentId` and `proxy`. A session can have a policy, an environment, both, or neither. See [Automation Policies](/concepts/policies) for details.
***
### proxy
* **Type:** `object | null`
* **Required:** No
* **Default:** `null`
* **Description:** Proxy configuration for the session. Routes all browser traffic through the specified proxy server. The proxy is applied at the device level, ensuring no IP leakage. Adds 2-3 seconds of cold-start latency per session.
**Two proxy sources are available:**
| Source | Description | Cost |
| -------- | ------------------------------------------------ | -------------------- |
| `WebRun` | WebRun assigns a residential proxy from its pool | \$4 per GB |
| `custom` | Bring your own HTTP or SOCKS proxy | No additional charge |
**WebRun Proxy Fields:**
| Field | Type | Required | Description |
| --------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source` | `string` | Yes | `"WebRun"` |
| `country` | `string` | Yes | ISO 3166-1 alpha-2 country code (e.g. `"US"`, `"GB"`, `"DE"`) or `"random"` |
| `level` | `string` | No | Proxy level: `"system"` or `"chrome"`. When omitted, routed to the best available connection that matches the country. `system` applies the proxy at the system level (no IP leakage, slower cold start). `chrome` applies the proxy to Chrome directly (faster cold start, may leak IP in edge cases like WebRTC). |
**Custom Proxy Fields:**
| Field | Type | Required | Description |
| ---------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `source` | `string` | Yes | `"custom"` |
| `type` | `string` | Yes | `"http"` or `"socks"` |
| `host` | `string` | Yes | Proxy server hostname or IP |
| `port` | `string` | Yes | Proxy server port |
| `username` | `string` | No | Authentication username |
| `password` | `string` | No | Authentication password |
| `level` | `string` | No | Proxy level: `"system"` or `"chrome"`. When omitted, routed to the best available connection. See WebRun proxy fields for details. |
**Examples:**
```json theme={null}
// WebRun-managed proxy (default level)
{
"proxy": {
"source": "WebRun",
"country": "US"
}
}
// WebRun-managed proxy with system level
{
"proxy": {
"source": "WebRun",
"country": "US",
"level": "system"
}
}
// Custom HTTP proxy
{
"proxy": {
"source": "custom",
"type": "http",
"host": "proxy.example.com",
"port": "8080",
"username": "user",
"password": "pass"
}
}
// Custom SOCKS proxy
{
"proxy": {
"source": "custom",
"type": "socks",
"host": "proxy.example.com",
"port": "1080",
"username": "user",
"password": "pass"
}
}
// No proxy (default)
{
"proxy": null
}
```
The `proxy` field is a top-level session parameter, alongside `environmentId`. It is not nested inside `task`. The proxy applies to the entire session. All tasks within the session use the same proxy.
See [Proxies guide](/usage-guides/proxies) for use cases and best practices.
***
### mode
* **Type:** `string`
* **Required:** No
* **Default:** `"default"`
* **Description:** Session mode. Currently only `"default"` is supported.
**Example:**
```json theme={null}
{
"mode": "default"
}
```
***
### reachOutMode
* **Type:** `string`, one of `"off"`, `"guardrail_only"`, `"full"`
* **Required:** No
* **Default:** `"guardrail_only"`
* **Description:** Controls whether the chat-connected user (Telegram, WhatsApp, Slack, Discord, Teams) on the session's [environment](/environments/overview) receives proactive messages from this session. The chat user is only contacted when no client is actively watching the session (no polling or WebSocket subscriber). This is a top-level session parameter and applies for the lifetime of the session.
**Allowed values:**
| Value | Behavior |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| `"off"` | No proactive messages. Guardrails and results stay on the API/WebSocket channel only. |
| `"guardrail_only"` | Bot pings the chat user only when the session hits a guardrail (CAPTCHA, 2FA, verification, login, etc.). This is the default. |
| `"full"` | Bot pings on guardrails **and** on `task_completed` with the task result delivered to chat. |
**Validation:** Invalid values return `400 Bad Request` with the error message `reachOutMode must be one of: off, guardrail_only, full`.
**Example:**
```json theme={null}
{
"environmentId": "683a1f2e4b0c1d2e3f4a5b6c",
"reachOutMode": "full",
"mode": "default",
"task": {
"prompt": "Export the monthly financial report"
}
}
```
The mode is locked at session creation. To change the behavior, create a new session. See [Routing Guardrails to a Chat User](/usage-guides/handling-guardrails#routing-guardrails-to-a-chat-user) for the full flow.
***
### task
* **Type:** `object`
* **Required:** No
* **Description:** Configuration for the task to run when the session starts. Contains all task-specific parameters.
**Example with structured\_json:**
```json theme={null}
{
"mode": "default",
"task": {
"prompt": "Find the price of iPhone 15 Pro on Apple.com",
"startingUrl": "https://apple.com",
"maxDuration": 300000,
"outputType": "structured_json",
"outputSchema": {
"type": "object",
"properties": {
"productName": { "type": "string" },
"price": { "type": "number" },
"currency": { "type": "string" }
}
}
}
}
```
**Example with structured\_csv:**
```json theme={null}
{
"mode": "default",
"task": {
"prompt": "Get the top 10 cryptocurrency prices",
"maxDuration": 300000,
"outputType": "structured_csv",
"outputSchema": ["name", "price", "market_cap"]
}
}
```
All task-specific parameters like `prompt`, `startingUrl`, `outputType`, and `outputSchema` are now nested inside the `task` object.
***
## Task Parameters
Parameters used inside the `task` object when creating a session, or in the message body when sending a new task via `POST /start/send-message`.
### prompt
* **Type:** `string`
* **Required:** No
* **Default:** `""`
* **Description:** Task description for the AI agent to execute.
**Example:**
```json theme={null}
{
"task": {
"prompt": "Go to amazon.com and search for wireless keyboards"
}
}
```
***
### startingUrl
* **Type:** `string`
* **Required:** No
* **Default:** `null`
* **Description:** URL where the browser should navigate before starting the task. Speeds up task execution by starting at the relevant page.
**Example:**
```json theme={null}
{
"task": {
"prompt": "Search for laptops",
"startingUrl": "https://amazon.com"
}
}
```
Setting a `startingUrl` eliminates the need to navigate from a blank page, reducing task execution time and cost.
***
### maxDuration
* **Type:** `number` (milliseconds)
* **Required:** No
* **Default:** `300000` (5 minutes)
* **Maximum:** `300000` (5 minutes)
* **Description:** Maximum time a task can run before automatic termination.
**Example:**
```json theme={null}
{
"maxDuration": 180000 // 3 minutes
}
```
Tasks automatically terminate after `maxDuration`. Set this value based on your expected task completion time.
***
### maxInputTokens
* **Type:** `number`
* **Required:** No
* **Default:** `100000`
* **Description:** Maximum number of input tokens the AI can process. Limits context size to control costs.
**Example:**
```json theme={null}
{
"maxInputTokens": 50000
}
```
***
### maxOutputTokens
* **Type:** `number`
* **Required:** No
* **Default:** `100000`
* **Description:** Maximum number of output tokens the AI can generate. Limits response size to control costs.
**Example:**
```json theme={null}
{
"maxOutputTokens": 50000
}
```
***
### terminateOnCompletion
* **Type:** `boolean`
* **Required:** No
* **Default:** `false`
* **Description:** Whether to automatically terminate the session after the current task completes. Set to `true` to prevent idle session charges.
**Example:**
```json theme={null}
{
"terminateOnCompletion": true
}
```
**Cost Optimization:** Set `terminateOnCompletion: true` on your last task to automatically close the session and prevent idle charges.
***
### outputType
* **Type:** `string`
* **Required:** No
* **Default:** `"text"`
* **Values:** `"text"`, `"structured_json"`, `"structured_csv"`
* **Description:** Specifies the output format.
| Value | Description | Schema Format |
| ----------------- | --------------------------------- | --------------------- |
| `text` | Markdown formatted text (default) | Not required |
| `structured_json` | Validated JSON output | JSON Schema object |
| `structured_csv` | CSV formatted data | Array of column names |
**Examples:**
```json theme={null}
// Text output (default)
{
"outputType": "text"
}
// JSON output with schema
{
"outputType": "structured_json",
"outputSchema": {
"type": "object",
"properties": {
"name": { "type": "string" },
"price": { "type": "number" }
}
}
}
// CSV output with column names
{
"outputType": "structured_csv",
"outputSchema": ["name", "price", "quantity"]
}
```
When using `outputType: "structured_json"` or `"structured_csv"`, you must also provide an `outputSchema` to define the expected response structure.
***
### outputSchema
* **Type:** `object` (JSON Schema) or `array` (column names)
* **Required:** No (required when `outputType` is `"structured_json"` or `"structured_csv"`)
* **Description:** Defines the expected response structure. The format depends on the `outputType`:
* For `structured_json`: A JSON Schema object
* For `structured_csv`: An array of column name strings
**Example for structured\_json:**
```json theme={null}
{
"outputType": "structured_json",
"outputSchema": {
"type": "object",
"properties": {
"title": { "type": "string" },
"price": { "type": "number" },
"inStock": { "type": "boolean" },
"features": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["title", "price"],
"additionalProperties": false
}
}
```
**Supported JSON Schema Types:**
* `string` - Text values
* `number` - Numeric values (integers and decimals)
* `boolean` - True/false values
* `object` - Nested objects with defined properties
* `array` - Arrays with defined item structure
**Example for structured\_csv:**
```json theme={null}
{
"outputType": "structured_csv",
"outputSchema": ["name", "price", "quantity", "category"]
}
```
The CSV output will include a header row with the specified column names, followed by data rows.
For JSON schemas, use `"additionalProperties": false` to ensure the output contains only the fields you specify.
***
### secrets
* **Type:** `array`
* **Required:** No
* **Default:** `[]`
* **Description:** Array of secret entries to provide credentials for websites the agent visits. Secrets are matched by domain pattern so the agent uses the right credentials for each site.
**Secret Entry Structure:**
| Field | Type | Required | Description |
| -------- | -------- | -------- | ------------------------------------------------------------------------------ |
| `match` | `string` | Yes | Domain pattern to match (e.g. `*.salesforce.com`) or `all` to match every site |
| `fields` | `object` | Yes | Key-value pairs of credential fields (e.g. `email`, `password`, `apiKey`) |
**Example:**
```json theme={null}
{
"secrets": [
{
"match": "*.salesforce.com",
"fields": {
"email": "user@company.com",
"password": "secretpass"
}
},
{
"match": "all",
"fields": {
"email": "user@company.com",
"password": "defaultpass"
}
}
]
}
```
Secrets are never stored in a database or persisted anywhere. They are only attached to the active session and immediately discarded once the session is destroyed. Secrets are never included in task output or webhook payloads.
See [Secrets guide](/usage-guides/secrets) for matching rules, custom fields, and best practices.
***
### files
* **Type:** `string[]` (array of file ID strings)
* **Required:** No
* **Default:** `[]`
* **Description:** Array of file IDs (returned from `POST /files/upload`) to attach to a task. The agent can use these files during browser automation, for example, uploading a document to a website form. This is a task-level parameter. Place it alongside `prompt`.
**Example with /start/run-task:**
```json theme={null}
{
"prompt": "Upload this document to the submission form",
"startingUrl": "https://example.com/upload",
"files": ["abc123...", "def456..."]
}
```
**Example with /start/start-session:**
```json theme={null}
{
"mode": "default",
"task": {
"prompt": "Upload the attached file to the portal",
"startingUrl": "https://example.com/portal",
"files": ["abc123..."]
}
}
```
See [File Uploads guide](/environments/file-uploads) for the full upload workflow.
***
### webhook
* **Type:** `object`
* **Required:** No
* **Description:** Webhook configuration for receiving task completion notifications.
**Webhook Object Structure:**
| Field | Type | Required | Description |
| --------------- | -------- | -------- | ----------------------------------- |
| `name` | `string` | Yes | Identifier for this webhook |
| `url` | `string` | Yes | Endpoint URL to receive the webhook |
| `auth` | `string` | No | Authorization header value |
| `submittedData` | `string` | Yes | Data to include in the payload |
**submittedData Options:**
* `"ai_response"` - The response from the AI (text, structured\_json, or structured\_csv), only the results/output from the LLM
* `"full_response"` - Full body response that includes the usage info
* `"just_ping"` - Just a ping notification, no data payload
**Example:**
```json theme={null}
{
"webhook": {
"name": "Product Webhook",
"url": "https://api.yoursite.com/webhooks/products",
"auth": "Bearer your-secret-token",
"submittedData": "ai_response"
}
}
```
**Complete Example with Structured Output and Webhook:**
```json theme={null}
{
"mode": "default",
"task": {
"prompt": "Extract product information from the page",
"startingUrl": "https://example.com/product",
"maxDuration": 300000,
"outputType": "structured_json",
"outputSchema": {
"type": "object",
"properties": {
"title": { "type": "string" },
"price": { "type": "number" },
"inStock": { "type": "boolean" }
},
"required": ["title", "price"],
"additionalProperties": false
},
"webhook": {
"name": "Product Webhook",
"url": "https://api.mysite.com/products",
"auth": "Bearer token123",
"submittedData": "ai_response"
}
}
}
```
***
## Task Parameters
Parameters used when starting a new task via `POST /start/send-message` with `actionType: "newTask"`.
All [Task Parameters](#task-parameters) are available, plus:
### actionType
* **Type:** `string`
* **Required:** Yes
* **Values:** `"newTask"`, `"state"`, `"interaction"`, `"guardrail"`
* **Description:** Type of action to perform on the session.
**Example:**
```json theme={null}
{
"actionType": "newTask"
}
```
***
### newState
* **Type:** `string`
* **Required:** Yes (for `actionType: "newTask"` and `actionType: "state"`)
* **Values:**
* For tasks: `"start"`
* For state control: `"pause"`, `"resume"`, `"stop"`, `"terminate"`
* **Description:** State change to apply.
**Examples:**
```json theme={null}
// Starting a new task
{
"actionType": "newTask",
"newState": "start"
}
// Pausing execution
{
"actionType": "state",
"newState": "pause"
}
// Resuming execution
{
"actionType": "state",
"newState": "resume"
}
```
***
## Message Parameters
Parameters used in the `message` field of `POST /start/send-message`.
### For State Control (actionType: "state")
**Required Parameters:**
* `actionType`: `"state"`
* `newState`: `"pause" | "resume" | "stop" | "terminate"`
**Example:**
```json theme={null}
{
"sessionId": "a1b2c3d4e5f6",
"message": {
"actionType": "state",
"newState": "pause"
}
}
```
***
### For Manual Interaction (actionType: "interaction")
**Required Parameters:**
* `actionType`: `"interaction"`
* `action`: Object containing interaction details
**Action Object Structure:**
#### takeOverControl / releaseControl
```json theme={null}
{
"type": "takeOverControl"
}
// or
{
"type": "releaseControl"
}
```
#### CLICK / DOUBLE\_CLICK
```json theme={null}
{
"type": "CLICK", // or "DOUBLE_CLICK"
"x": 500,
"y": 300
}
```
**Parameters:**
* `x` (number): Horizontal coordinate (0-1024)
* `y` (number): Vertical coordinate (155-600, accounting for browser chrome)
**Coordinate System:** The browser viewport is 1024×600 pixels. The top 155 pixels are browser chrome (not clickable). Clickable area is 1024×445 pixels starting at Y=155.
#### TYPE
```json theme={null}
{
"type": "TYPE",
"text": "Hello world",
"humanLike": true
}
```
**Parameters:**
* `text` (string, required): Text to type
* `humanLike` (boolean, optional): Simulate human typing speed
#### KEY\_PRESS
```json theme={null}
{
"type": "KEY_PRESS",
"key": "Enter"
}
```
**Parameters:**
* `key` (string, required): Key to press
**Common Keys:**
* `Enter`
* `Escape`
* `Tab`
* `Backspace`
* `ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight`
***
### For Guardrail Response (actionType: "guardrail")
**Required Parameters:**
* `actionType`: `"guardrail"`
* `prompt`: Human-provided information
* `newState`: `"resume"`
**Example:**
```json theme={null}
{
"sessionId": "a1b2c3d4e5f6",
"message": {
"actionType": "guardrail",
"prompt": "Username: user@example.com, Password: pass123",
"newState": "resume"
}
}
```
***
## Response Fields
Fields returned in API responses.
### Session Response Fields
Returned from `POST /start/start-session`:
| Field | Type | Description |
| ---------------------- | ------- | --------------------------------------------- |
| `success` | boolean | Whether the request succeeded |
| `sessionId` | string | Unique session identifier |
| `socketURL` | string | WebSocket connection URL |
| `streaming` | object | Video streaming configuration |
| `streaming.webRTCURL` | string | WebRTC WHEP endpoint URL |
| `streaming.webViewURL` | string | HTTP video stream URL |
| `streaming.dimensions` | object | Video dimensions `{width: 1024, height: 600}` |
| `initialPrompt` | string | The initial task that was provided |
| `expiresIn` | number | Session expiration time in milliseconds |
| `balance` | number | Current account balance in USD |
| `message` | string | Additional information |
***
### Task Response Fields
Returned from `POST /start/send-message` with `actionType: "newTask"` and `POST /start/run-task`:
**When task completes within 50 seconds:**
| Field | Type | Description |
| ------------------------------- | ------- | ------------------------------- |
| `success` | boolean | Whether the request succeeded |
| `sessionId` | string | Session identifier |
| `taskId` | string | Task identifier |
| `status` | string | Task status: `"complete"` |
| `result` | object | Task result details |
| `result.type` | string | Result type: `"task_completed"` |
| `result.data` | object | Result data |
| `result.data.message` | string | Task completion message |
| `result.data.prompt_tokens` | number | Input tokens used |
| `result.data.completion_tokens` | number | Output tokens generated |
| `result.data.total_tokens` | number | Total tokens used |
| `result.data.completion_time` | number | Task execution time in seconds |
**When task is still running after 50 seconds:**
| Field | Type | Description |
| ----------- | ------- | --------------------------------- |
| `success` | boolean | Whether the request succeeded |
| `sessionId` | string | Session identifier |
| `taskId` | string | Task identifier for polling |
| `status` | string | Task status: `"pending"` |
| `pending` | boolean | `true` when task is still running |
| `pollUrl` | string | URL to poll for task result |
| `message` | string | Instruction to poll for result |
***
### Poll Response Fields
Returned from `GET /task/:sessionId/:taskId`:
**While running:**
| Field | Type | Description |
| -------------------- | ------- | --------------------------------- |
| `success` | boolean | Whether the request succeeded |
| `status` | string | Task status: `"active"` |
| `pending` | boolean | `true` when task is still running |
| `usage` | object | Current usage statistics |
| `usage.inputTokens` | number | Input tokens used so far |
| `usage.outputTokens` | number | Output tokens generated so far |
| `usage.computeTime` | number | Compute time in seconds |
| `usage.cost` | number | Cost in USD so far |
**When completed:**
| Field | Type | Description |
| ------------------------ | ------- | -------------------------------- |
| `success` | boolean | Whether the request succeeded |
| `type` | string | Result type: `"task_completed"` |
| `data` | object | Task result data |
| `data.message` | string | Task completion message |
| `data.prompt_tokens` | number | Total input tokens used |
| `data.completion_tokens` | number | Total output tokens generated |
| `data.total_tokens` | number | Total tokens used |
| `data.completion_time` | number | Task execution time in seconds |
| `usage` | object | Final usage statistics |
| `usage.inputTokens` | number | Total input tokens |
| `usage.outputTokens` | number | Total output tokens |
| `usage.computeTime` | number | Total compute time in seconds |
| `usage.cost` | number | Total cost in USD |
| `completedAt` | string | ISO 8601 timestamp of completion |
**When guardrail triggered:**
| Field | Type | Description |
| ------------ | ------- | --------------------------------------------- |
| `success` | boolean | Whether the request succeeded |
| `type` | string | Result type: `"guardrail_trigger"` |
| `data` | object | Guardrail details |
| `data.type` | string | Guardrail type (e.g., `"human_input_needed"`) |
| `data.value` | string | Guardrail message explaining what's needed |
**When failed:**
| Field | Type | Description |
| --------- | ------- | ----------------------------------------- |
| `success` | boolean | `false` |
| `status` | string | `"failed"` |
| `error` | string | Error message |
| `code` | string | Error code (e.g., `"NAVIGATION_TIMEOUT"`) |
| `usage` | object | Usage statistics up to failure |
***
### Usage Object Structure
The `usage` object provides token and cost information:
```typescript theme={null}
{
inputTokens: number; // Number of input tokens used
outputTokens: number; // Number of output tokens generated
computeTime: number; // Compute time in seconds
cost: number; // Cost in USD
}
```
**Example:**
```json theme={null}
{
"usage": {
"inputTokens": 12450,
"outputTokens": 3200,
"computeTime": 5,
"cost": 0.0124
}
}
```
***
## OpenAI-Compatible Parameters
Parameters for `POST /v1/chat/completions`.
### model
* **Type:** `string`
* **Required:** Yes
* **Value:** `"webrun-browser-1"`
* **Description:** Model to use. Currently only `webrun-browser-1` is available.
***
### messages
* **Type:** `array` of message objects
* **Required:** Yes
* **Description:** Array of conversation messages
**Message Object Structure:**
```typescript theme={null}
{
role: "system" | "user" | "assistant";
content: string;
}
```
**Example:**
```json theme={null}
{
"messages": [
{
"role": "system",
"content": "You are a helpful browser automation assistant."
},
{
"role": "user",
"content": "Go to example.com and extract all headings"
}
]
}
```
***
### stream
* **Type:** `boolean`
* **Required:** No
* **Default:** `false`
* **Description:** Enable streaming responses via Server-Sent Events (SSE).
***
### max\_tokens
* **Type:** `number`
* **Required:** No
* **Default:** `2000`
* **Description:** Maximum number of tokens in the response.
***
### temperature
* **Type:** `number`
* **Required:** No
* **Description:** Not used (included for OpenAI compatibility only). Task execution is deterministic.
***
## Type Definitions
### ActionType
```typescript theme={null}
type ActionType = "newTask" | "state" | "interaction" | "guardrail";
```
***
### StateType
```typescript theme={null}
type StateType = "start" | "pause" | "resume" | "stop" | "terminate";
```
***
### InteractionType
```typescript theme={null}
type InteractionType =
| "takeOverControl"
| "releaseControl"
| "CLICK"
| "DOUBLE_CLICK"
| "TYPE"
| "KEY_PRESS";
```
***
### OutputType
```typescript theme={null}
type OutputType = "text" | "structured_json" | "structured_csv";
```
***
### OutputSchema
For `structured_json`, use a JSON Schema object:
```typescript theme={null}
interface JsonOutputSchema {
type: "object" | "array" | "string" | "number" | "boolean";
properties?: Record;
items?: JsonOutputSchema;
required?: string[];
additionalProperties?: boolean;
}
```
For `structured_csv`, use an array of column names:
```typescript theme={null}
type CsvOutputSchema = string[];
```
Combined type:
```typescript theme={null}
type OutputSchema = JsonOutputSchema | CsvOutputSchema;
```
***
### WebhookConfig
```typescript theme={null}
interface WebhookConfig {
name: string;
url: string;
auth?: string;
submittedData: "ai_response" | "full_response" | "just_ping";
}
```
***
### SecretEntry
```typescript theme={null}
interface SecretEntry {
match: string; // Domain pattern (e.g. "*.salesforce.com") or "all"
fields: Record; // Key-value credential fields
}
```
***
\###TaskConfig
```typescript theme={null}
interface TaskConfig {
prompt?: string;
startingUrl?: string | null;
maxDuration?: number;
maxInputTokens?: number;
maxOutputTokens?: number;
terminateOnCompletion?: boolean;
outputType?: OutputType;
outputSchema?: OutputSchema;
webhook?: WebhookConfig;
secrets?: SecretEntry[];
files?: string[];
}
```
***
### ProxyConfig
```typescript theme={null}
// WebRun-managed proxy
interface WebRunProxy {
source: "WebRun";
country: string; // ISO 3166-1 alpha-2 code or "random"
level?: "system" | "chrome"; // Default: best available connection
}
// Custom proxy (HTTP or SOCKS)
interface CustomProxy {
source: "custom";
type: "http" | "socks";
host: string;
port: string;
username?: string;
password?: string;
level?: "system" | "chrome"; // Default: best available connection
}
type ProxyConfig = WebRunProxy | CustomProxy;
```
***
### SessionConfig
```typescript theme={null}
interface SessionConfig {
environmentId?: string;
policyId?: string;
proxy?: ProxyConfig | null;
reachOutMode?: "off" | "guardrail_only" | "full"; // Default: "guardrail_only"
mode?: string;
task?: TaskConfig;
}
```
***
### TaskMessage
```typescript theme={null}
interface TaskMessage {
actionType: "newTask";
newState: "start";
prompt: string;
startingUrl?: string | null;
maxDuration?: number;
maxInputTokens?: number;
maxOutputTokens?: number;
terminateOnCompletion?: boolean;
outputType?: OutputType;
outputSchema?: OutputSchema;
webhook?: WebhookConfig;
secrets?: SecretEntry[];
files?: string[];
}
```
***
### StateMessage
```typescript theme={null}
interface StateMessage {
actionType: "state";
newState: "pause" | "resume" | "stop" | "terminate";
}
```
***
### InteractionMessage
```typescript theme={null}
interface InteractionMessage {
actionType: "interaction";
action:
| { type: "takeOverControl" }
| { type: "releaseControl" }
| { type: "CLICK" | "DOUBLE_CLICK"; x: number; y: number }
| { type: "TYPE"; text: string; humanLike?: boolean }
| { type: "KEY_PRESS"; key: string };
}
```
***
### GuardrailMessage
```typescript theme={null}
interface GuardrailMessage {
actionType: "guardrail";
prompt: string;
newState: "resume";
}
```
***
## Parameter Validation
### Constraints
| Parameter | Min | Max | Notes |
| -------------------- | ---- | --------- | -------------------------------- |
| `maxDuration` | 1000 | 300000 | Milliseconds (max task duration) |
| `maxInputTokens` | 0 | 100000 | Default: 100000 |
| `maxOutputTokens` | 0 | 100000 | Default: 100000 |
| `max_tokens` | 0 | unlimited | OpenAI-compatible endpoint |
| Click `x` coordinate | 0 | 1024 | Browser width |
| Click `y` coordinate | 155 | 600 | Accounting for browser chrome |
***
Complete endpoint reference
Response format reference
# Rate Limits
Source: https://docs.webrun.ai/api-reference/rate-limits
Understanding and working with WebRun API rate limits
## Overview
WebRun enforces rate limits to ensure fair usage and system stability. Rate limits are applied per user (API key owner), not per API key.
Rate limits are **per user**, not per API key. If you have multiple API keys, they all share the same rate limit.
***
## Rate Limits by Endpoint
| Endpoint | Limit | Window | Notes |
| ------------------------------ | ----------- | ------------------- | -------------------------- |
| `POST /start/start-session` | 10 requests | per minute per user | Session creation |
| `POST /start/send-message` | 10 requests | per minute per user | All action types |
| `POST /start/run-task` | 10 requests | per minute per user | Single-task execution |
| `POST /v1/chat/completions` | 10 requests | per minute per user | OpenAI-compatible endpoint |
| `GET /task/:sessionId/:taskId` | No limit | - | Polling endpoint |
| `GET /v1/models` | No limit | - | Model listing |
| `GET /start/health` | No limit | - | Health check |
| `GET /start/active-sockets` | No limit | - | Active connections |
***
## Rate Limit Details
### Per-User Limits
All rate limits are tied to your user account, not individual API keys. This means:
* Creating multiple API keys **does not** increase your rate limit
* All requests from all your API keys count toward the same limit
* Rate limits reset every minute
**Example:**
```javascript theme={null}
// These all count toward the same 10/minute limit:
fetch('https://api.webrun.ai/start/run-task', {
headers: { 'Authorization': 'Bearer API_KEY_1' }
});
fetch('https://api.webrun.ai/start/run-task', {
headers: { 'Authorization': 'Bearer API_KEY_2' }
});
fetch('https://api.webrun.ai/start/run-task', {
headers: { 'Authorization': 'Bearer API_KEY_3' }
});
// Total: 3 requests toward your 10/minute limit
```
***
### Per-Minute Window
Rate limits use a sliding window of 60 seconds:
* At any given moment, you can make up to 10 requests
* The window slides continuously (not fixed to clock minutes)
* Requests older than 60 seconds ago don't count toward your limit
**Example Timeline:**
```
Time Action Requests in last 60s
00:00 Make 10 requests 10/10 (at limit)
00:30 Try another request Rate limited
01:00 First request expired 9/10 (space available)
01:00 Make new request 10/10 (at limit)
01:05 5 more requests expired 5/10 (space available)
```
***
### Unlimited Endpoints
Some endpoints have no rate limits:
* **`GET /task/:sessionId/:taskId`** - Poll as frequently as needed for task results
* **`GET /v1/models`** - Retrieve model list anytime
* **`GET /start/health`** - Monitor system health without restrictions
* **`GET /start/active-sockets`** - Check active connections anytime
Use polling endpoints freely for monitoring long-running tasks without worrying about rate limits.
***
## Rate Limit Headers
WebRun API responses include rate limit information in HTTP headers:
| Header | Description | Example |
| ----------------------- | -------------------------------------- | ------------ |
| `X-RateLimit-Limit` | Maximum requests per window | `10` |
| `X-RateLimit-Remaining` | Requests remaining in current window | `7` |
| `X-RateLimit-Reset` | Unix timestamp when limit resets | `1704067260` |
| `Retry-After` | Seconds until you can retry (429 only) | `30` |
**Example Response Headers:**
```
HTTP/1.1 200 OK
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 7
X-RateLimit-Reset: 1704067260
```
**Example 429 Response Headers:**
```
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1704067260
Retry-After: 30
```
***
## Handling 429 Errors
### Error Response Format
When you exceed the rate limit, you'll receive a `429 Too Many Requests` response:
```json theme={null}
{
"success": false,
"message": "Rate limit exceeded. Please try again later."
}
```
**HTTP Headers:**
```
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1704067260
Retry-After: 30
```
***
### Retry Strategy
Implement exponential backoff when handling rate limits:
```javascript theme={null}
async function makeRequestWithRetry(url, options, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch(url, options);
if (response.status === 429) {
const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
const backoffTime = Math.min(retryAfter * 1000, 60000); // Max 60s
console.log(`Rate limited. Retrying in ${retryAfter}s...`);
await new Promise(resolve => setTimeout(resolve, backoffTime));
continue;
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
if (attempt === maxRetries - 1) throw error;
// Exponential backoff for other errors
const backoffTime = Math.min(1000 * Math.pow(2, attempt), 30000);
await new Promise(resolve => setTimeout(resolve, backoffTime));
}
}
throw new Error('Max retries exceeded');
}
// Usage
const result = await makeRequestWithRetry(
'https://api.webrun.ai/start/run-task',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({ task: { prompt: 'Search Google for Anthropic' } })
}
);
```
***
### Check Rate Limit Before Request
Proactively check remaining rate limit from headers:
```javascript theme={null}
class RateLimitedClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.remaining = 10;
this.resetTime = Date.now();
}
async request(endpoint, options = {}) {
// Wait if rate limit is exhausted
if (this.remaining <= 0 && Date.now() < this.resetTime) {
const waitTime = this.resetTime - Date.now();
console.log(`Rate limit exhausted. Waiting ${waitTime}ms...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
}
const response = await fetch(`https://api.webrun.ai${endpoint}`, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${this.apiKey}`
}
});
// Update rate limit info from headers
this.remaining = parseInt(response.headers.get('X-RateLimit-Remaining') || '10');
this.resetTime = parseInt(response.headers.get('X-RateLimit-Reset') || Date.now()) * 1000;
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
}
// Usage
const client = new RateLimitedClient('YOUR_API_KEY');
const result = await client.request('/start/run-task', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ task: { prompt: 'Search Google' } })
});
```
***
## Best Practices
### 1. Batch Operations
Instead of making many small requests, combine operations into fewer requests:
**Bad - Multiple requests:**
```javascript theme={null}
// Each task is a separate request (10 requests)
for (let i = 0; i < 10; i++) {
await fetch('https://api.webrun.ai/start/run-task', {
method: 'POST',
headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' },
body: JSON.stringify({ task: { prompt: `Task ${i}` } })
});
}
// Rate limited after 10 requests
```
**Good - Use persistent sessions:**
```javascript theme={null}
// Create one session (1 request)
const session = await fetch('https://api.webrun.ai/start/start-session', {
method: 'POST',
headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' },
body: JSON.stringify({ task: { prompt: 'Initial task' } })
}).then(r => r.json());
// Run multiple tasks in same session (10 requests)
for (let i = 0; i < 10; i++) {
await fetch('https://api.webrun.ai/start/send-message', {
method: 'POST',
headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' },
body: JSON.stringify({
sessionId: session.sessionId,
message: { actionType: 'newTask', newState: 'start', prompt: `Task ${i}` }
})
});
}
// Total: 11 requests (still under limit if done quickly)
```
***
### 2. Use Polling Efficiently
Polling endpoints have no rate limit, so use them instead of creating new requests:
**Bad:**
```javascript theme={null}
// Repeatedly calling run-task to check status (hits rate limit)
while (true) {
const result = await fetch('https://api.webrun.ai/start/run-task', {
method: 'POST',
headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' },
body: JSON.stringify({ task: { prompt: 'Search Google' } })
}).then(r => r.json());
if (result.status === 'complete') break;
await new Promise(r => setTimeout(r, 2000));
}
```
**Good:**
```javascript theme={null}
// Create task once, then poll (unlimited)
const task = await fetch('https://api.webrun.ai/start/run-task', {
method: 'POST',
headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' },
body: JSON.stringify({ task: { prompt: 'Search Google' } })
}).then(r => r.json());
// Poll until complete (no rate limit)
while (true) {
const result = await fetch(task.pollUrl).then(r => r.json());
if (!result.pending) return result;
await new Promise(r => setTimeout(r, 2000));
}
```
***
### 3. Implement Request Queuing
Queue requests to stay within rate limits:
```javascript theme={null}
class RateLimitedQueue {
constructor(apiKey, requestsPerMinute = 10) {
this.apiKey = apiKey;
this.requestsPerMinute = requestsPerMinute;
this.queue = [];
this.processing = false;
this.requestTimes = [];
}
async enqueue(endpoint, options) {
return new Promise((resolve, reject) => {
this.queue.push({ endpoint, options, resolve, reject });
this.processQueue();
});
}
async processQueue() {
if (this.processing || this.queue.length === 0) return;
this.processing = true;
while (this.queue.length > 0) {
// Remove requests older than 60 seconds
const now = Date.now();
this.requestTimes = this.requestTimes.filter(time => now - time < 60000);
// Wait if at rate limit
if (this.requestTimes.length >= this.requestsPerMinute) {
const oldestRequest = this.requestTimes[0];
const waitTime = 60000 - (now - oldestRequest);
await new Promise(resolve => setTimeout(resolve, waitTime));
continue;
}
// Process next request
const { endpoint, options, resolve, reject } = this.queue.shift();
this.requestTimes.push(Date.now());
try {
const response = await fetch(`https://api.webrun.ai${endpoint}`, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${this.apiKey}`
}
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
resolve(await response.json());
} catch (error) {
reject(error);
}
}
this.processing = false;
}
}
// Usage
const queue = new RateLimitedQueue('YOUR_API_KEY');
// Enqueue 20 requests (will be automatically throttled)
const promises = [];
for (let i = 0; i < 20; i++) {
promises.push(
queue.enqueue('/start/run-task', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ task: { prompt: `Task ${i}` } })
})
);
}
const results = await Promise.all(promises);
console.log(`Completed ${results.length} tasks`);
```
***
### 4. Monitor Rate Limit Headers
Always check rate limit headers to avoid hitting limits:
```javascript theme={null}
async function monitoredRequest(url, options) {
const response = await fetch(url, options);
const limit = response.headers.get('X-RateLimit-Limit');
const remaining = response.headers.get('X-RateLimit-Remaining');
const reset = response.headers.get('X-RateLimit-Reset');
console.log(`Rate Limit: ${remaining}/${limit} remaining`);
console.log(`Resets at: ${new Date(reset * 1000).toISOString()}`);
if (parseInt(remaining) <= 2) {
console.warn(' Approaching rate limit!');
}
return await response.json();
}
```
***
### 5. Use WebSocket for Real-Time Updates
WebSocket connections don't count toward rate limits:
**Bad - Polling via REST:**
```javascript theme={null}
// Each poll is a rate-limited request
setInterval(async () => {
const status = await fetch('https://api.webrun.ai/start/send-message', {
method: 'POST',
headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' },
body: JSON.stringify({
sessionId: 'abc123',
message: { actionType: 'state', newState: 'status' }
})
}).then(r => r.json());
console.log(status);
}, 5000);
// Hits rate limit quickly
```
**Good - WebSocket events:**
```javascript theme={null}
import { io } from 'socket.io-client';
const socket = io('https://api.webrun.ai', {
auth: { sessionId: 'abc123' }
});
socket.on('message', (data) => {
console.log('Real-time update:', data);
});
// No rate limit, real-time updates
```
***
## Common Rate Limit Scenarios
### Scenario 1: Batch Processing
**Problem:** Need to process 100 tasks
**Solution:** Create sessions and spread requests over time
```javascript theme={null}
const queue = new RateLimitedQueue('YOUR_API_KEY', 10);
// Create 10 sessions (takes 1 minute)
const sessions = [];
for (let i = 0; i < 10; i++) {
sessions.push(
queue.enqueue('/start/start-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({})
})
);
}
await Promise.all(sessions);
// Run 10 tasks per session (takes 10 minutes total)
for (let i = 0; i < 100; i++) {
const sessionIndex = i % 10;
queue.enqueue('/start/send-message', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
sessionId: sessions[sessionIndex].sessionId,
message: {
actionType: 'newTask',
newState: 'start',
prompt: `Task ${i}`
}
})
});
}
```
***
### Scenario 2: Real-Time Monitoring
**Problem:** Need to monitor multiple sessions in real-time
**Solution:** Use WebSocket instead of REST polling
```javascript theme={null}
import { io } from 'socket.io-client';
const sessions = ['session1', 'session2', 'session3'];
sessions.forEach(sessionId => {
const socket = io('https://api.webrun.ai', {
auth: { sessionId }
});
socket.on('message', (data) => {
console.log(`[${sessionId}]`, data);
});
});
// No rate limits, real-time updates for all sessions
```
***
### Scenario 3: Burst Traffic
**Problem:** Occasional bursts of 20-30 requests
**Solution:** Implement request queuing with automatic throttling
```javascript theme={null}
// Use the RateLimitedQueue from earlier
const queue = new RateLimitedQueue('YOUR_API_KEY', 10);
// Handle burst (automatically throttled)
async function handleBurst(tasks) {
const promises = tasks.map(task =>
queue.enqueue('/start/run-task', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ task: { prompt: task } })
})
);
return await Promise.all(promises);
}
// Process 30 tasks (automatically spread over 3 minutes)
const tasks = Array.from({ length: 30 }, (_, i) => `Task ${i}`);
const results = await handleBurst(tasks);
```
***
## FAQ
### Can I increase my rate limit?
Currently, rate limits are fixed at 10 requests per minute per user. Enterprise plans with higher rate limits may be available in the future.
### Do WebSocket connections count toward rate limits?
No. WebSocket connections and messages do not count toward rate limits. Only REST API requests are rate limited.
### What happens if I hit the rate limit?
You'll receive a `429 Too Many Requests` response with a `Retry-After` header indicating how long to wait before retrying.
### Are rate limits shared across API keys?
Yes. Rate limits are per user, not per API key. All your API keys share the same rate limit.
### Can I check my current rate limit usage?
Yes. Check the `X-RateLimit-Remaining` header in any API response to see how many requests you have left in the current window.
### Do failed requests count toward the rate limit?
Yes. All requests count toward the rate limit, including those that fail with 4xx or 5xx errors.
***
## Next Steps
Complete endpoint reference
Parameter documentation
Response format reference
Error handling guide
# Response Formats
Source: https://docs.webrun.ai/api-reference/response-formats
Complete reference for all WebRun API response formats
## Overview
WebRun provides two ways to receive responses:
| Method | How It Works | Best For |
| ------------- | -------------------------------------------------------------------- | ------------------------------------------ |
| **REST** | Results returned inline if task completes within 50s, otherwise poll | Stateless, serverless, simple integrations |
| **WebSocket** | Real-time events pushed as they occur | Real-time UIs, live monitoring |
***
## REST API Response Formats
### Inline Results (\< 50 seconds)
Both `/run-task` and `/send-message` wait up to 50 seconds for task completion. If the task finishes in time, you get the result immediately.
**Structure:**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"type": "task_completed",
"data": {
"message": "Successfully completed the search",
"files": [
{
"source": "https://example.com/report.zip",
"downloadUrl": "https://blobs.webrun.ai/files/report.zip",
"filename": "report.zip",
"timestamp": 1771138379108
}
],
"network": [
{
"id": "tevo9",
"taskId": "x9y8z7w6v5u4",
"urls": [
{
"url": "https://example.com/api/data",
"timestamp": 1771138379087.646
}
]
}
]
},
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"completion_time": 23.5,
"cost": 0.0124
}
}
```
**Response Fields:**
| Field | Type | Description |
| --------------------------------- | ------- | ---------------------------------------------------------- |
| `success` | boolean | Request success indicator |
| `sessionId` | string | Session identifier |
| `taskId` | string | Task identifier |
| `type` | string | Result type: `"task_completed"` |
| `data` | object | Task result data |
| `data.message` | string | Task completion message |
| `data.files` | array | Files downloaded during task execution (optional) |
| `data.files[].source` | string | Original URL the file was downloaded from |
| `data.files[].downloadUrl` | string | WebRun-hosted URL to download the file |
| `data.files[].filename` | string | Name of the downloaded file |
| `data.files[].timestamp` | number | Unix timestamp (ms) when the file was downloaded |
| `data.network` | array | Network requests captured during task execution (optional) |
| `data.network[].id` | string | Unique identifier for the network entry |
| `data.network[].taskId` | string | Task that generated the network activity |
| `data.network[].urls` | array | URLs requested in this network entry |
| `data.network[].urls[].url` | string | Full URL of the network request |
| `data.network[].urls[].timestamp` | number | Unix timestamp (ms) of the request |
| `usage` | object | Usage and billing information |
| `usage.prompt_tokens` | number | Input tokens used |
| `usage.completion_tokens` | number | Output tokens generated |
| `usage.total_tokens` | number | Total tokens used |
| `usage.completion_time` | number | Execution time in seconds |
| `usage.cost` | number | Cost in USD |
***
### Pending Results (> 50 seconds)
For longer tasks, the response returns immediately with a poll URL.
**Structure:**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"status": "pending",
"pending": true,
"pollUrl": "https://api.webrun.ai/task/a1b2c3d4e5f6/x9y8z7w6v5u4",
"message": "Task still running. Poll GET /task/:sessionId/:taskId for result."
}
```
**Response Fields:**
| Field | Type | Description |
| ----------- | ------- | --------------------------------- |
| `success` | boolean | Request success indicator |
| `sessionId` | string | Session identifier |
| `taskId` | string | Task identifier for polling |
| `status` | string | Task status: `"pending"` |
| `pending` | boolean | `true` when task is still running |
| `pollUrl` | string | URL to poll for task result |
| `message` | string | Instruction to poll for result |
***
### Polling Responses
Poll `GET /task/:sessionId/:taskId` until `pending: false` or a final `type` is returned.
#### Still Running
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"status": "running",
"usage": {
"prompt_tokens": 8000,
"completion_tokens": 2100,
"total_tokens": 10100,
"completion_time": 12.3,
"cost": 0.0067
}
}
```
**Response Fields:**
| Field | Type | Description |
| ----------- | ------- | ----------------------------------------------- |
| `success` | boolean | Request success indicator |
| `sessionId` | string | Session identifier |
| `taskId` | string | Task identifier |
| `status` | string | `"running"` - task is executing |
| `usage` | object | Current usage statistics (updates in real-time) |
***
#### Task Completed
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"type": "task_completed",
"data": {
"message": "Task finished successfully",
"files": [
{
"source": "https://example.com/report.zip",
"downloadUrl": "https://blobs.webrun.ai/files/report.zip",
"filename": "report.zip",
"timestamp": 1771138379108
}
],
"network": [
{
"id": "tevo9",
"taskId": "x9y8z7w6v5u4",
"urls": [
{
"url": "https://example.com/api/data",
"timestamp": 1771138379087.646
}
]
}
]
},
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"completion_time": 23.5,
"cost": 0.0124
},
"completedAt": "2024-01-15T10:30:00Z"
}
```
**Response Fields:**
| Field | Type | Description |
| --------------------------------- | ------- | ---------------------------------------------------------- |
| `success` | boolean | Request success indicator |
| `sessionId` | string | Session identifier |
| `taskId` | string | Task identifier |
| `type` | string | `"task_completed"` |
| `data` | object | Task result data |
| `data.message` | string | Completion message |
| `data.files` | array | Files downloaded during task execution (optional) |
| `data.files[].source` | string | Original URL the file was downloaded from |
| `data.files[].downloadUrl` | string | WebRun-hosted URL to download the file |
| `data.files[].filename` | string | Name of the downloaded file |
| `data.files[].timestamp` | number | Unix timestamp (ms) when the file was downloaded |
| `data.network` | array | Network requests captured during task execution (optional) |
| `data.network[].id` | string | Unique identifier for the network entry |
| `data.network[].taskId` | string | Task that generated the network activity |
| `data.network[].urls` | array | URLs requested in this network entry |
| `data.network[].urls[].url` | string | Full URL of the network request |
| `data.network[].urls[].timestamp` | number | Unix timestamp (ms) of the request |
| `usage` | object | Final usage statistics |
| `usage.prompt_tokens` | number | Total input tokens |
| `usage.completion_tokens` | number | Total output tokens |
| `usage.total_tokens` | number | Total tokens |
| `usage.completion_time` | number | Execution time in seconds |
| `usage.cost` | number | Cost in USD |
| `completedAt` | string | ISO 8601 completion timestamp |
***
#### Guardrail Triggered
```json theme={null}
{
"success": true,
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "I need login credentials to proceed"
}
}
```
**Response Fields:**
| Field | Type | Description |
| ------------ | ------- | -------------------------------- |
| `success` | boolean | Request success indicator |
| `type` | string | `"guardrail_trigger"` |
| `data` | object | Guardrail details |
| `data.type` | string | Guardrail type |
| `data.value` | string | Message explaining what's needed |
**Next Steps:**
Respond with guardrail message via `POST /start/send-message`:
```json theme={null}
{
"sessionId": "a1b2c3d4e5f6",
"message": {
"actionType": "guardrail",
"prompt": "Username: user@example.com, Password: pass123",
"newState": "resume"
}
}
```
***
#### Task Failed
```json theme={null}
{
"success": false,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"status": "failed",
"error": "Navigation timeout after 30 seconds",
"code": "NAVIGATION_TIMEOUT",
"usage": {
"prompt_tokens": 5000,
"completion_tokens": 1200,
"total_tokens": 6200,
"completion_time": 30.0,
"cost": 0.0045
}
}
```
**Response Fields:**
| Field | Type | Description |
| --------- | ------- | ------------------------------ |
| `success` | boolean | `false` |
| `status` | string | `"failed"` |
| `error` | string | Error message |
| `code` | string | Error code |
| `usage` | object | Usage statistics up to failure |
***
### Session Creation Response
`POST /start/start-session` returns session details and streaming configuration.
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"socketURL": "https://api.webrun.ai",
"streaming": {
"webRTCURL": "https://a1b2c3d4e5f6.webrun.ai/whep",
"webViewURL": "https://a1b2c3d4e5f6.webrun.ai",
"dimensions": {
"width": 1024,
"height": 600
}
},
"initialPrompt": "Go to amazon.com",
"expiresIn": 300000,
"balance": 12.50,
"message": "Connect to instance using sessionId in auth"
}
```
**Response Fields:**
| Field | Type | Description |
| ---------------------- | ------- | ----------------------------- |
| `success` | boolean | Request success indicator |
| `sessionId` | string | Unique session identifier |
| `socketURL` | string | WebSocket connection URL |
| `streaming` | object | Video streaming configuration |
| `streaming.webRTCURL` | string | WebRTC WHEP endpoint |
| `streaming.webViewURL` | string | HTTP video stream URL |
| `streaming.dimensions` | object | Video dimensions |
| `initialPrompt` | string | Initial task provided |
| `expiresIn` | number | Session expiration time (ms) |
| `balance` | number | Current account balance (USD) |
| `message` | string | Additional information |
***
### State Control Response
`POST /start/send-message` with `actionType: "state"`, `"interaction"`, or `"guardrail"` returns immediate confirmation.
```json theme={null}
{
"success": true,
"message": "Message sent successfully"
}
```
**Response Fields:**
| Field | Type | Description |
| --------- | ------- | ------------------------- |
| `success` | boolean | Request success indicator |
| `message` | string | Confirmation message |
***
## WebSocket Event Formats
Connect via Socket.IO and listen for `message` events:
```javascript theme={null}
socket.on("message", (data) => {
console.log(data.type, data);
});
```
### Event: agent
Live agent thoughts and reasoning during task execution.
```json theme={null}
{
"type": "agent",
"content": "I'll navigate to the search box and enter the query..."
}
```
**Fields:**
| Field | Type | Description |
| --------- | ------ | -------------------- |
| `type` | string | `"agent"` |
| `content` | string | Agent reasoning text |
***
### Event: action
Browser action performed by the agent.
```json theme={null}
{
"type": "action",
"data": {
"name": "click_element"
}
}
```
**Fields:**
| Field | Type | Description |
| ----------- | ------ | -------------- |
| `type` | string | `"action"` |
| `data` | object | Action details |
| `data.name` | string | Action name |
***
### Event: response\_update
Status update during task execution.
```json theme={null}
{
"type": "response_update",
"data": {
"message": "Starting task... Browsing the web now."
}
}
```
**Fields:**
| Field | Type | Description |
| -------------- | ------ | ------------------- |
| `type` | string | `"response_update"` |
| `data` | object | Update details |
| `data.message` | string | Status message |
***
### Event: task\_completed
Task finished successfully.
```json theme={null}
{
"type": "task_completed",
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"data": {
"message": "Task completed successfully",
"files": [
{
"source": "https://example.com/report.zip",
"downloadUrl": "https://blobs.webrun.ai/files/report.zip",
"filename": "report.zip",
"timestamp": 1771138379108
}
],
"network": [
{
"id": "tevo9",
"taskId": "x9y8z7w6v5u4",
"urls": [
{
"url": "https://example.com/api/data",
"timestamp": 1771138379087.646
}
]
}
]
},
"usage": {
"prompt_tokens": 15420,
"completion_tokens": 8230,
"total_tokens": 23650,
"completion_time": 45.3,
"cost": 0.0234
}
}
```
**Fields:**
| Field | Type | Description |
| --------------------------------- | ------ | ---------------------------------------------------------- |
| `type` | string | `"task_completed"` |
| `sessionId` | string | Session identifier |
| `taskId` | string | Task identifier |
| `data` | object | Completion details |
| `data.message` | string | Completion message |
| `data.files` | array | Files downloaded during task execution (optional) |
| `data.files[].source` | string | Original URL the file was downloaded from |
| `data.files[].downloadUrl` | string | WebRun-hosted URL to download the file |
| `data.files[].filename` | string | Name of the downloaded file |
| `data.files[].timestamp` | number | Unix timestamp (ms) when the file was downloaded |
| `data.network` | array | Network requests captured during task execution (optional) |
| `data.network[].id` | string | Unique identifier for the network entry |
| `data.network[].taskId` | string | Task that generated the network activity |
| `data.network[].urls` | array | URLs requested in this network entry |
| `data.network[].urls[].url` | string | Full URL of the network request |
| `data.network[].urls[].timestamp` | number | Unix timestamp (ms) of the request |
| `usage` | object | Usage statistics |
| `usage.prompt_tokens` | number | Input tokens used |
| `usage.completion_tokens` | number | Output tokens generated |
| `usage.total_tokens` | number | Total tokens used |
| `usage.completion_time` | number | Execution time (seconds) |
| `usage.cost` | number | Cost in USD |
***
### Event: guardrail\_trigger
Agent needs human input to continue.
```json theme={null}
{
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "I need login credentials to proceed"
}
}
```
**Fields:**
| Field | Type | Description |
| ------------ | ------ | -------------------------------- |
| `type` | string | `"guardrail_trigger"` |
| `data` | object | Guardrail details |
| `data.type` | string | Guardrail type |
| `data.value` | string | Message explaining what's needed |
**Respond with:**
```javascript theme={null}
socket.emit("message", {
actionType: "guardrail",
prompt: "Username: demo@example.com, Password: demo123",
newState: "resume"
});
```
***
### Event: error
Task failed with error.
```json theme={null}
{
"type": "error",
"error": "Navigation timeout after 30 seconds",
"code": "NAVIGATION_TIMEOUT"
}
```
**Fields:**
| Field | Type | Description |
| ------- | ------ | ------------- |
| `type` | string | `"error"` |
| `error` | string | Error message |
| `code` | string | Error code |
***
### Connection Events
#### connect
Socket connected successfully.
```javascript theme={null}
socket.on("connect", () => {
console.log("Connected to session");
});
```
***
#### disconnect
Socket disconnected.
```javascript theme={null}
socket.on("disconnect", () => {
console.log("Disconnected from session");
});
```
***
#### error
Socket error occurred.
```javascript theme={null}
socket.on("error", (err) => {
console.error("Socket error:", err);
});
```
***
#### end\_session
Session terminated by server.
```json theme={null}
{
"reason": "completed"
}
```
**Possible Reasons:**
* `"completed"` - Task completed
* `"terminated"` - Manually terminated
* `"expired"` - Session expired due to inactivity
* `"terminateOnCompletion"` - Auto-terminated after task
* `"instance_lost"` - Instance connection lost
```javascript theme={null}
socket.on("end_session", (data) => {
console.log("Session ended:", data.reason);
});
```
***
#### instance:disconnected
Instance connection lost. Session enters grace period for reconnection.
```json theme={null}
{
"gracePeriod": 300000
}
```
```javascript theme={null}
socket.on("instance:disconnected", (data) => {
console.log("Instance lost, waiting for reconnection...");
console.log("Grace period:", data.gracePeriod, "ms");
});
```
***
#### instance:reconnected
Instance connection recovered.
```javascript theme={null}
socket.on("instance:reconnected", (data) => {
console.log("Instance reconnected");
});
```
***
## OpenAI-Compatible Response Formats
### Non-Streaming Response
`POST /v1/chat/completions` with `stream: false` (default).
```json theme={null}
{
"id": "chatcmpl-a1b2c3d4e5f6",
"object": "chat.completion",
"created": 1704067200,
"model": "webrun-browser-1",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "I found 5 headings on example.com:\n1. Example Domain\n2. More Information\n3. Contact\n4. About\n5. Privacy Policy"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 8450,
"completion_tokens": 2100,
"total_tokens": 10550
},
"webrun": {
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"cost": 0.0089
}
}
```
**Response Fields:**
| Field | Type | Description |
| ---------------------------- | ------ | -------------------------------- |
| `id` | string | Completion identifier |
| `object` | string | `"chat.completion"` |
| `created` | number | Unix timestamp |
| `model` | string | Model name: `"webrun-browser-1"` |
| `choices` | array | Array of completion choices |
| `choices[0].index` | number | Choice index (always 0) |
| `choices[0].message` | object | Assistant message |
| `choices[0].message.role` | string | `"assistant"` |
| `choices[0].message.content` | string | Response text |
| `choices[0].finish_reason` | string | `"stop"` |
| `usage` | object | Token usage statistics |
| `usage.prompt_tokens` | number | Input tokens |
| `usage.completion_tokens` | number | Output tokens |
| `usage.total_tokens` | number | Total tokens |
| `webrun` | object | WebRun-specific metadata |
| `webrun.sessionId` | string | Session identifier |
| `webrun.taskId` | string | Task identifier |
| `webrun.cost` | number | Cost in USD |
***
### Streaming Response (SSE)
`POST /v1/chat/completions` with `stream: true` returns Server-Sent Events.
**Stream Format:**
```
data: {"id":"chatcmpl-a1b2c3","object":"chat.completion.chunk","created":1704067200,"model":"webrun-browser-1","choices":[{"index":0,"delta":{"role":"assistant","content":"I"},"finish_reason":null}]}
data: {"id":"chatcmpl-a1b2c3","object":"chat.completion.chunk","created":1704067200,"model":"webrun-browser-1","choices":[{"index":0,"delta":{"content":" found"},"finish_reason":null}]}
data: {"id":"chatcmpl-a1b2c3","object":"chat.completion.chunk","created":1704067200,"model":"webrun-browser-1","choices":[{"index":0,"delta":{"content":" 5"},"finish_reason":null}]}
data: {"id":"chatcmpl-a1b2c3","object":"chat.completion.chunk","created":1704067200,"model":"webrun-browser-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
```
**Chunk Structure:**
| Field | Type | Description |
| -------------------------- | ------ | ------------------------------------- |
| `id` | string | Completion identifier |
| `object` | string | `"chat.completion.chunk"` |
| `created` | number | Unix timestamp |
| `model` | string | `"webrun-browser-1"` |
| `choices` | array | Array of delta choices |
| `choices[0].index` | number | Choice index (always 0) |
| `choices[0].delta` | object | Content delta |
| `choices[0].delta.role` | string | `"assistant"` (first chunk only) |
| `choices[0].delta.content` | string | Text chunk |
| `choices[0].finish_reason` | string | `null` during stream, `"stop"` at end |
**Handling Streams:**
```javascript theme={null}
import OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'https://api.webrun.ai/v1',
apiKey: 'YOUR_API_KEY'
});
const stream = await client.chat.completions.create({
model: 'webrun-browser-1',
messages: [{ role: 'user', content: 'Go to example.com' }],
stream: true
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}
```
***
## Error Response Format
All errors follow this standard format:
```json theme={null}
{
"success": false,
"message": "Human-readable error message"
}
```
**Common HTTP Status Codes:**
| Status | Meaning | Example Message |
| ------ | --------------------- | ------------------------------------------------ |
| 200 | Success | - |
| 400 | Bad request | `"sessionId and message are required"` |
| 401 | Unauthorized | `"Invalid or revoked API key"` |
| 402 | Payment required | `"Insufficient balance."` |
| 403 | Forbidden | `"Account is deactivated"` |
| 404 | Not found | `"Session not found"` |
| 429 | Too many requests | `"Rate limit exceeded. Please try again later."` |
| 500 | Internal server error | `"Internal server error"` |
| 503 | Service unavailable | `"No available instances."` |
See [Rate Limits](/api-reference/rate-limits) for handling 429 errors.
***
## Usage Object Structure
The `usage` object appears in many responses and provides token and cost information:
```typescript theme={null}
interface Usage {
prompt_tokens: number; // Number of input tokens used
completion_tokens: number; // Number of output tokens generated
total_tokens: number; // Total tokens (prompt + completion)
completion_time: number; // Execution time in seconds
cost: number; // Cost in USD
}
```
**Example:**
```json theme={null}
{
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"completion_time": 23.5,
"cost": 0.0124
}
}
```
***
## Complete Event Reference Table
| Event Type | REST | WebSocket | Description |
| ----------------------- | ---------- | --------- | -------------------------- |
| `agent` | No | Yes | Live agent reasoning |
| `action` | No | Yes | Browser action performed |
| `response_update` | No | Yes | Status updates |
| `task_completed` | Yes (poll) | Yes | Task finished successfully |
| `guardrail_trigger` | Yes (poll) | Yes | Human input needed |
| `error` | Yes (poll) | Yes | Task failed |
| `end_session` | No | Yes | Session terminated |
| `instance:disconnected` | No | Yes | Instance connection lost |
| `instance:reconnected` | No | Yes | Instance recovered |
***
## Next Steps
Complete endpoint reference
Parameter documentation
Detailed event handling guide
WebSocket integration guide
# Supported Interactions
Source: https://docs.webrun.ai/capabilities/supported-interactions
Every element type WebRun's AI agent can interact with on the web
WebRun's AI agent can interact with most element types on the web: standard forms, dynamic SPAs, legacy portals, and everything in between. No custom configuration or selectors required.
***
## Form Inputs
Fill any text field, search box, or textarea with context-aware content
Complete multi-step forms with validation and dynamic fields
Navigate dropdown menus and select appropriate options
Select dates, times, and navigate calendar widgets
***
## Interactive Elements
Click buttons, submit forms, and trigger any interactive elements
Handle modal dialogs, popups, and overlay interactions
Extract and interact with complex table structures and data grids
Control playback and interact with embedded media
Read, analyze, and extract data directly from embedded or linked PDF files
***
## Authentication & Security
Enter one-time passwords and complete two-factor authentication
Solve image challenges, reCAPTCHAs, and verification systems
***
## File Transfers
Download files from any website: documents, reports, images, CSVs, and more
Upload files to other websites and platforms as part of cross-site transfer workflows
File transfers let you move data between platforms autonomously. Combine downloads and uploads in a single workflow to handle tasks like exporting a report from one system and uploading it to another: no manual intervention needed.
***
## Dynamic Content
React to AJAX updates, infinite scroll, and real-time changes
Navigate and interact with embedded iframe content
***
## Why This Matters
Traditional automation tools like Playwright or Puppeteer require you to write explicit selectors for every element. When websites change their HTML structure, your scripts break.
WebRun's AI agent **understands the visual and semantic context** of web pages. It identifies elements by their purpose, not their code, so your automations keep working even when websites update their design.
**Example:** Instead of writing `document.querySelector('.btn-primary-v2')`, you tell WebRun: "Click the submit button."
***
## Next Steps
Run your first task in 5 minutes
Learn how human-in-the-loop works
# Bot Identification
Source: https://docs.webrun.ai/concepts/bot-identification
How WebRun identifies its automated browser traffic so networks like Cloudflare can recognize and verify it as a good bot
WebRun runs AI agents inside real browsers on behalf of users. So that site operators, CDNs, and bot-management providers such as [Cloudflare](https://developers.cloudflare.com/bots/concepts/bot/verified-bots/) can recognize this traffic - and tell it apart from spoofed or malicious automation - WebRun publishes a stable, verifiable bot identity.
This page is the canonical, public reference for that identity. It documents the User-Agent, the cryptographic and network-level ways to verify a request genuinely originates from WebRun, and the behavior operators can expect. It also serves as the public documentation required by Cloudflare's [Verified Bots](https://developers.cloudflare.com/bots/concepts/bot/verified-bots/) program.
Verifying identity matters. A malicious client can copy WebRun's User-Agent string, but it cannot forge a valid [message signature](#http-message-signatures-web-bot-auth) or originate from WebRun's [published egress IPs](#ip-ranges-and-reverse-dns). Always verify before allow-listing.
***
## User-Agent
WebRun's automated traffic identifies itself with the **`WebRunAgent`** product token in the User-Agent header:
```
Mozilla/5.0 (compatible; WebRunAgent/1.0; +https://docs.webrun.ai/bot)
```
| Field | Value |
| ------------- | -------------------------------------------------------------------------- |
| Product token | `WebRunAgent` |
| Version | `1.0` (major version increments only on breaking changes to this identity) |
| Info URL | `https://docs.webrun.ai/bot` (redirects here) |
| Operator | WebRun - `webrun.ai` |
| Category | AI Agent - acts on a user's behalf, user-initiated |
The token meets Cloudflare's [Verified Bots policy](https://developers.cloudflare.com/bots/concepts/bot/verified-bots/policy/) requirements for a User-Agent: it is longer than five characters, contains no special characters, and is unique to WebRun.
The underlying browser can still present a standard Chrome User-Agent for individual page rendering (see [What User-Agent does WebRun use?](/troubleshooting/faqs#what-user-agent-does-webrun-use)). The `WebRunAgent` token and the verification methods below are how WebRun's traffic is **identified and authenticated at the network layer** - they do not depend on the browser's rendering User-Agent, so match on the [signature](#http-message-signatures-web-bot-auth) or [egress IP](#ip-ranges-and-reverse-dns) when you need a spoof-proof signal.
***
## Verifying WebRun traffic
Use either method below to confirm a request is genuinely from WebRun. Message signatures are preferred - they verify each request independently and are Cloudflare's recommended method - with IP-range and reverse-DNS validation available as a fallback for operators who filter by network.
### HTTP Message Signatures (Web Bot Auth)
WebRun signs its requests using [HTTP Message Signatures](https://www.rfc-editor.org/rfc/rfc9421.html), the mechanism behind Cloudflare's [Web Bot Auth](https://developers.cloudflare.com/bots/reference/bot-verification/web-bot-auth/). Each request carries `Signature` and `Signature-Input` headers signed with a key published in WebRun's public key directory:
```
https://webrun.ai/.well-known/http-message-signatures-directory
```
To verify:
Retrieve the JSON Web Key Set from `https://webrun.ai/.well-known/http-message-signatures-directory`. Cache it and refresh periodically; keys rotate.
Read the `keyid` from the request's `Signature-Input` header and select the matching public key from the directory.
Verify the `Signature` header over the covered components per [RFC 9421](https://www.rfc-editor.org/rfc/rfc9421.html). A valid signature proves the request came from WebRun and was not tampered with in transit.
Cloudflare customers do not need to implement this manually. Once WebRun is approved in the Verified Bots directory, signed WebRun requests are matched automatically and exposed through the `cf.bot_management.verified_bot` field.
### IP ranges and reverse DNS
WebRun's identifiable agent traffic originates from a stable, published set of egress IP ranges. The authoritative, machine-readable list is served at:
```
https://webrun.ai/bot/ip-ranges.json
```
Always fetch the live list - do not hardcode individual addresses. Ranges change as capacity scales, and the JSON endpoint is the single source of truth. Requests routed through [WebRun-managed or custom proxies](/usage-guides/proxies) intentionally exit from proxy IPs and will **not** appear in this list.
Each egress IP is also validated with **forward-confirmed reverse DNS**. To verify an IP without the range list:
Run a reverse DNS (PTR) lookup on the source IP. WebRun addresses resolve to a hostname under `bot.webrun.ai`, for example `edge-203-0-113-7.bot.webrun.ai`.
Run a forward DNS (A/AAAA) lookup on that hostname and confirm it resolves back to the original source IP. This forward-confirmation step is what makes the check spoof-resistant - never trust the PTR record alone.
***
## Expected behavior
WebRun operates as a transparent, well-behaved agent. Operators can expect the following from `WebRunAgent` traffic:
* **User-initiated, not mass crawling.** Traffic is generated by explicit user automation tasks running in isolated [browser sessions](/concepts/sessions), not by autonomous, large-scale site indexing.
* **No automated CAPTCHA solving or bot-defense evasion.** When a CAPTCHA or challenge is encountered, the session pauses for human takeover - WebRun does not attempt to defeat it programmatically (see [handling CAPTCHAs](/troubleshooting/faqs#how-do-i-handle-captchas)).
* **Respects rate-limiting signals.** WebRun honors `429 Too Many Requests` responses and the `Retry-After` header, and backs off accordingly.
* **Honors `robots.txt`.** WebRun observes `robots.txt` directives that target the `WebRunAgent` token (see [Controlling WebRun](#controlling-webrun-traffic)).
* **Isolated, ephemeral sessions.** Each session is a clean browser instance with no shared cookies, cache, or state, destroyed on termination.
* **Encrypted transport.** All WebRun traffic uses HTTPS/TLS.
***
## Cloudflare Verified Bots
WebRun participates in Cloudflare's [Verified Bots](https://developers.cloudflare.com/bots/concepts/bot/verified-bots/) program so that Cloudflare-protected sites can distinguish legitimate WebRun traffic from spoofed automation and apply their own allow, challenge, or rate-limit policies to it.
**If you run a Cloudflare-protected site**, you can identify verified WebRun requests using the [`cf.bot_management.verified_bot`](https://developers.cloudflare.com/ruleset-engine/rules-language/fields/reference/cf.bot_management.verified_bot/) field in a WAF custom rule, and allow-list them following Cloudflare's [guide for allowing verified bots](https://developers.cloudflare.com/waf/custom-rules/use-cases/allow-traffic-from-verified-bots/).
**For the WebRun team**, the Verified Bots application is submitted from the Cloudflare dashboard under **Manage Account → Configurations → Bot Submission Form**, using this page as the required public documentation, the `WebRunAgent` User-Agent, and the message-signature key directory above.
***
## Controlling WebRun traffic
Site operators can allow, throttle, or disallow WebRun using standard mechanisms.
### robots.txt
Target the `WebRunAgent` token directly:
```txt Allow everything theme={null}
User-agent: WebRunAgent
Allow: /
```
```txt Disallow a section theme={null}
User-agent: WebRunAgent
Disallow: /private/
```
```txt Disallow entirely theme={null}
User-agent: WebRunAgent
Disallow: /
```
### Firewall / WAF rules
Match on the [verified-bot signal](#cloudflare-verified-bots) or the `WebRunAgent` User-Agent to allow, rate-limit, or block WebRun at the edge. Prefer matching the verified-bot field or a [validated signature](#verifying-webrun-traffic) over the raw User-Agent string, since the User-Agent alone can be spoofed.
Blocking WebRun blocks the automation your own users have asked WebRun to run on your site. If WebRun traffic is causing load problems, consider rate-limiting or [contacting us](#reporting-abuse) before an outright block.
***
## Reporting abuse
If you believe WebRun traffic is misbehaving on your site, email **[abuse@webrun.ai](mailto:abuse@webrun.ai)** with the affected domain, timestamps (with timezone), and a sample of request logs (source IP and User-Agent). Verified reports are investigated promptly.
For general questions, contact [support@webrun.ai](mailto:support@webrun.ai).
***
Route sessions through proxy IPs instead of WebRun's egress ranges
How WebRun's isolated browser sessions work
Runtime rules that constrain agent behavior
Technical details, including the browser User-Agent
# Guardrails
Source: https://docs.webrun.ai/concepts/guardrails
Human-in-the-loop safety mechanism for sensitive operations
## What are Guardrails?
Guardrails are WebRun's safety mechanism for human-in-the-loop control. When the AI agent encounters a situation requiring human judgment or sensitive information, it pauses the task and triggers a guardrail.
This ensures the agent never:
* Submits credentials without explicit permission
* Makes purchases or financial transactions autonomously
* Proceeds when instructions are ambiguous
* Bypasses security challenges like CAPTCHAs
***
## When Guardrails Trigger
| Trigger Type | Example Scenario | Agent Response |
| ------------------------- | ------------------------------ | ------------------------------------------------------- |
| **Credentials Needed** | Login form encountered | "I need login credentials to proceed" |
| **Purchase Confirmation** | Checkout page reached | "Do you want me to complete this purchase?" |
| **CAPTCHA Detected** | Security challenge appears | "A CAPTCHA is blocking me. Please solve it." |
| **Ambiguous Instruction** | Multiple valid interpretations | "Which item should I click? There are several options." |
| **Security Warning** | SSL error or warning page | "I encountered a security warning. Should I proceed?" |
***
## Guardrail Flow
When a guardrail is triggered, the workflow pauses and waits for human input:
```
Task Running
↓
Guardrail Triggered (task pauses)
↓
Human Provides Input
↓
Agent Resumes (task continues)
↓
Task Completes
```
### Detection Methods
**REST API (Polling):**
```json theme={null}
{
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "I need login credentials to proceed"
}
}
```
**WebSocket (Real-time):**
```javascript theme={null}
socket.on("message", (data) => {
if (data.type === "guardrail_trigger") {
console.log("Guardrail:", data.data.value);
// Handle guardrail response
}
});
```
***
## Guardrail Response Format
### Request from Agent
```json theme={null}
{
"success": true,
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "I need login credentials for this website"
}
}
```
### Response to Agent
Provide the requested information and resume the task:
**REST:**
```bash theme={null}
POST /start/send-message
{
"sessionId": "SESSION_ID",
"message": {
"actionType": "guardrail",
"prompt": "Username: demo@example.com, Password: demo123",
"newState": "resume"
}
}
```
**WebSocket:**
```javascript theme={null}
socket.emit("message", {
actionType: "guardrail",
prompt: "Username: demo@example.com, Password: demo123",
newState": "resume"
});
```
***
## Common Guardrail Types
### 1. Credentials Request
**Trigger:** Login form detected
**Agent Message:** "I need login credentials to proceed"
**Response:** Provide username and password
**Example:**
```javascript theme={null}
prompt: "Username: user@example.com, Password: secretpass123"
```
### 2. Purchase Confirmation
**Trigger:** Checkout or payment page reached
**Agent Message:** "Do you want me to complete this purchase? The total is \$49.99"
**Response:** Confirm or deny
**Example:**
```javascript theme={null}
prompt: "Yes, complete the purchase"
// or
prompt: "No, stop and return to cart"
```
### 3. Ambiguous Choice
**Trigger:** Multiple valid options exist
**Agent Message:** "Which product should I select? I see 3 options with similar names"
**Response:** Clarify the choice
**Example:**
```javascript theme={null}
prompt: "Select the first one (Logitech K380)"
```
### 4. CAPTCHA or Security Challenge
**Trigger:** CAPTCHA appears
**Agent Message:** "A CAPTCHA is blocking me. Please solve it."
**Response:** Either solve it manually or instruct to skip
**Example:**
```javascript theme={null}
prompt: "I've solved the CAPTCHA, please continue"
// or use manual takeover to solve it yourself
```
***
## Policy-Triggered Guardrails
When a session has an [automation policy](/concepts/policies) attached, the policy can trigger guardrails automatically. If a policy rule is set to **guardrail** enforcement (rather than block), the session pauses and waits for your approval, exactly like a credential or CAPTCHA guardrail. Handle policy guardrails the same way you handle any other guardrail in your integration.
***
## How Guardrails Behave
The agent asks for clarification rather than guessing. Financial transactions, account changes, and data submissions always trigger a guardrail; the agent won't act on these autonomously.
WebRun doesn't store credentials. You provide them on-demand when a guardrail triggers, or upfront using [secrets](/usage-guides/secrets). You can also intervene manually at any point, even if no guardrail has triggered.
For unattended automations, guardrails can also be answered through a connected chat user (Telegram, WhatsApp, Slack, Discord, Teams) on the session's environment, so a scheduled task can pause and wait for a human reply over chat instead of failing. This is controlled per-session via the `reachOutMode` parameter (`"off"`, `"guardrail_only"`, or `"full"`), which defaults to `"guardrail_only"`. See [Handling Guardrails](/usage-guides/handling-guardrails#routing-guardrails-to-a-chat-user).
***
## Handling Guardrails in Code
### Basic Pattern (REST)
```javascript theme={null}
async function handleTask(sessionId, taskId, apiKey) {
// Poll for result
const result = await pollForResult(sessionId, taskId, apiKey);
if (result.type === "guardrail_trigger") {
console.log("Guardrail:", result.data.value);
// Get user input
const userInput = await promptUser(result.data.value);
// Respond to guardrail
await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
message: {
actionType: "guardrail",
prompt: userInput,
newState: "resume"
}
})
});
// Continue polling for completion
return await pollForResult(sessionId, taskId, apiKey);
}
return result;
}
```
### Advanced Pattern (WebSocket)
```javascript theme={null}
function setupGuardrailHandler(socket) {
socket.on("message", async (data) => {
if (data.type === "guardrail_trigger") {
const userInput = await promptUser(data.data.value);
socket.emit("message", {
actionType: "guardrail",
prompt: userInput,
newState: "resume"
});
}
});
}
```
***
## Automated Guardrail Handling
For common scenarios, you can build automated guardrail handlers:
```javascript theme={null}
const guardrailHandlers = {
"login credentials": () => {
return `Username: ${process.env.USERNAME}, Password: ${process.env.PASSWORD}`;
},
"purchase": (message) => {
const amount = extractAmount(message);
return amount < 100 ? "Yes, proceed" : "No, cancel";
},
"captcha": () => {
return "Skip this task, CAPTCHA detected";
}
};
function handleGuardrail(message) {
for (const [trigger, handler] of Object.entries(guardrailHandlers)) {
if (message.toLowerCase().includes(trigger)) {
return handler(message);
}
}
// Default: ask human
return promptUser(message);
}
```
***
## Avoiding Guardrails with Secrets
If you know the credentials the agent will need ahead of time, you can provide them upfront using the `secrets` parameter. This lets the agent authenticate automatically without triggering a guardrail or pausing the task.
```json theme={null}
{
"task": {
"prompt": "Log in and export the report",
"secrets": [
{
"match": "*.example.com",
"fields": { "email": "user@example.com", "password": "pass123" }
}
]
}
}
```
Secrets are never stored; they exist only in the session's memory and are discarded when the session ends.
[Secrets guide](/usage-guides/secrets)
***
## Related
Provide credentials upfront to avoid guardrails
Implementation guide with examples
Take manual control of sessions
Understanding task lifecycle
Runtime rules that can trigger guardrails automatically
# Automation Policies
Source: https://docs.webrun.ai/concepts/policies
Runtime rules that control what an AI agent can and cannot do during a session
## Overview
An Automation Policy is a reusable set of rules that sits between the agent's intent and actual execution. When an agent attempts an action (navigate to a URL, type text into a form, download a file) the policy enforcement layer checks it against your rules in real-time and either allows it, blocks it, or pauses the session for human approval.
Policies are created and managed in the [dashboard](https://app.webrun.ai). You attach them to sessions by passing `policyId` when starting a session or task.
***
## How It Works
Every action the agent attempts passes through the policy enforcement layer:
1. **Agent produces an action** (click, type, navigate, download, etc.)
2. **All matching rules are evaluated**
3. **The most restrictive outcome wins:**
* **Block**: action is silently prevented, agent is told to find an alternative, session continues
* **Guardrail**: session pauses, you review and approve/reject (uses the same [guardrail mechanism](/concepts/guardrails) you already handle)
* **Allow**: action executes normally
**Precedence: Block > Guardrail > Allow.** If any rule says block, the action is blocked, even if other rules allow it.
***
## Creating a Policy
Policies are created in the dashboard at **Policies → New Policy**.
1. Give the policy a **name** and optional **description**
2. Optionally set an **LLM Role** to guide agent behavior (see [LLM Role](#llm-role) below)
3. Add rules across **Domain Rules** and **Action Rules** (see [Rule Types](#rule-types) below)
4. Save as **Active** (ready to use) or **Draft** (work in progress)
Policies are reusable. Create once, attach to any number of sessions.
***
## Attaching a Policy to a Session
Pass `policyId` as a top-level parameter when starting a session, the same level as `environmentId`.
### REST API
```bash start-session theme={null}
curl -X POST https://api.webrun.ai/start/start-session \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"environmentId": "683a1f2e4b0c1d2e3f4a5b6c",
"policyId": "pol_xyz789",
"task": {
"prompt": "Extract the latest invoice from the vendor portal",
"startingUrl": "https://vendor.example.com"
}
}'
```
```bash run-task theme={null}
curl -X POST https://api.webrun.ai/start/run-task \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"policyId": "pol_xyz789",
"prompt": "Check current pricing on example.com",
"startingUrl": "https://example.com"
}'
```
### MCP
The `policyId` field is available on `create_session` and `browser_task`.
### Playground
Select a policy from the dropdown in the session configuration panel, alongside the environment selector. A policy summary shows which rules are active before you start.
A session can have a policy, an environment, both, or neither.
***
## Rule Types
A policy contains an optional LLM Role plus one or more rule groups. You can combine Domain Rules and Action Rules in a single policy.
### LLM Role
Free-text instructions injected into the agent's system prompt when the policy is active. Use this to shape the agent's overall behavior, for example:
> *"You are a research assistant. Only browse educational sites. Never fill out forms."*
LLM Role accepts up to **2,000 characters** and is applied before any rule evaluation. It complements rules by giving the agent behavioral context rather than hard enforcement.
***
### Domain Rules
Control which websites the agent can visit. Three modes:
| Mode | Behavior |
| ----------------------- | ----------------------------------------------------------------- |
| **Allow All** (default) | Agent can visit any domain unless explicitly blocked |
| **Allowlist** | Agent can only visit domains you list. Everything else is blocked |
| **Blocklist** | Agent can visit everything except domains you list |
Each domain entry specifies a pattern and an action (block or guardrail).
**Pattern matching:**
| Pattern | Matches | Doesn't Match |
| --------------- | -------------------------------------------------- | -------------------- |
| `example.com` | `example.com` | `sub.example.com` |
| `*.example.com` | `sub.example.com`, `deep.sub.example.com` | `example.com` itself |
| `*example.com` | `example.com`, `sub.example.com`, `badexample.com` | `other.com` |
***
### Action Rules
Permit, block, or guardrail entire categories of agent behavior. Action Rules now also cover URL pattern matching (for Navigation) and regex-based data sensitivity detection.
How a rule is configured depends on its **category**:
* **Navigation** category: shows a **URL Pattern** field instead of scope/match options. Use glob-style patterns to target specific paths (e.g., `*/admin/*`, `*/checkout*`). This replaces the need for standalone URL pattern rules.
* **All other categories**: show **Scope** (`All`, `Target`, or `Page`), **Match Type** (`Keyword` or `Regex`), and **Match** fields. Use Regex match type to detect sensitive data patterns like credit card numbers, SSNs, or API keys.
| Category | Details | Permission |
| ------------------- | ------------------------------------ | ---------- |
| **Navigation** | `*/admin/*` | Block |
| **Type / Keyboard** | Regex: `\b\d{3}-\d{2}-\d{4}\b` (All) | Block |
| **Shell Command** | All | Block |
| **Click** | Keyword: "delete" (Target) | Guardrail |
**Scope** controls where the match is checked:
| Scope | What it checks |
| ---------- | ----------------------------------------------------------- |
| **All** | All available context for the action |
| **Target** | The element or value the agent is directly interacting with |
| **Page** | Visible content on the current page |
**Action categories and their WebRun actions:**
| Category | WebRun Actions |
| ------------------- | -------------------------------------------- |
| **Navigation** | navigateUrl, goBack, goForward, pageRefresh |
| **Click** | CLICK, DOUBLE\_CLICK, MOUSE\_DOWN, MOUSE\_UP |
| **Type / Keyboard** | TYPE, KEY\_PRESS, COPY |
| **File Download** | File transfer events (download) |
| **File Upload** | File transfer events (upload) |
| **Form Submit** | KEY\_PRESS with Enter on form elements |
| **Screenshot** | captureScreenshot |
| **Shell Command** | Shell/terminal execution |
| **Clipboard** | selectAll + copy, paste operations |
| **Tab Management** | newTab, setActiveTab, closeTab |
| **Scroll** | SCROLL |
| **Mouse Move** | MOVE\_MOUSE |
Each category can be set to **allow**, **block**, or **guardrail**. You also set a **default action** for any category not explicitly listed.
**Example:** a read-only research agent might block navigation to `*/admin/*`, block typing with a regex for credit card numbers, block all file uploads, and guardrail clicks matching "delete".
**URL patterns in Navigation rules** replace the need for standalone URL pattern rules. To allow a domain but block specific paths (e.g., allow `salesforce.com` but block `salesforce.com/admin/*`), add a Navigation action rule with the pattern `*/admin/*` set to Block.
***
## Enforcement Outcomes
### Block
The action is silently prevented. The agent receives a message that the action was blocked by policy and is told to find an alternative. The session continues. Only the specific action is stopped. Blocked actions are logged to the audit trail.
**When to use:** Hard security boundaries: never access competitor sites, never type SSNs, never execute shell commands.
### Guardrail
The session pauses and you're prompted to approve, reject, or take over. This uses the same [guardrail mechanism](/concepts/guardrails) as credential prompts and CAPTCHAs. Handle it the same way in your integration.
**When to use:** Sensitive but legitimate operations: logging into financial sites, actions that need human judgment, workflows where occasional manual review is expected.
See [Handling Guardrails](/usage-guides/handling-guardrails) for integration details on detecting and responding to guardrails via REST, WebSocket, and MCP.
***
## Policy Templates
Pre-built policy templates are available in the dashboard as starting points. Select a template when creating a new policy, then customize.
Read-only browsing. Blocks typing, file uploads, shell commands. Guardrails on form submits. Action rules with regex matching for sensitive data patterns (credit cards, SSNs, API keys). Navigation action rules blocking `*/admin/*` and `*/settings/*`.
Guardrails on banking and payment domains. Action rules block typing keywords `transfer funds` and `wire transfer`. Navigation action rules with guardrails on checkout pages. Action rules with regex matching to block sensitive data extraction.
Allowlist mode (only approved medical portals). Action rules with regex matching to block SSN patterns. Action rules guardrail on medical term keywords and patient pages. Blocks file uploads, guardrails on screenshots. Action rules with regex matching for medical record number patterns.
Allowlist mode with explicit domains only. Guardrails on all typed text. Blocks shell commands and file uploads. Navigation action rules blocking all admin, delete, and settings paths. Action rules with regex matching for all sensitive data patterns.
***
## Audit Trail
Every enforcement decision is logged with:
* **Timestamp**
* **Action** the agent attempted
* **Rule** that matched
* **Decision** (allow, block, or guardrail)
* **Your response** (if guardrail)
* **Session ID** and **Policy ID**
The audit trail is immutable and exportable for compliance reporting.
***
## Related
Human-in-the-loop mechanism used by guardrail enforcement
Integration guide for detecting and responding to guardrails
Persistent browser profiles, files, and credentials
Session lifecycle and configuration
Provide credentials upfront to avoid guardrail interruptions
Complete API parameter reference including policyId
# Pricing & Costs
Source: https://docs.webrun.ai/concepts/pricing
Understanding WebRun's pricing model and cost optimization
WebRun charges for **token usage**, **compute time**, and **proxy data transfer** (when using WebRun-managed proxies).
## What Tasks Cost
Real examples from production usage:
| Task Type | Typical Cost | Duration |
| -------------------------------- | ------------ | -------- |
| Simple search (Google, LinkedIn) | \$0.01 | \~20s |
| Form filling (3-5 fields) | \$0.02 | \~25s |
| Data extraction (10-20 items) | \$0.05 | \~50s |
| Multi-step workflow (5+ tasks) | \$0.08 | \~2min |
| Complex automation (10+ tasks) | \$0.30 | \~5min |
Actual costs vary based on page complexity and task specificity.
***
## Pricing
### Tokens
| Model | Input (per 1M tokens) | Output (per 1M tokens) |
| ----------------------- | --------------------- | ---------------------- |
| **webrun-browser-pro** | \$0.60 | \$2.70 |
| **webrun-browser-fast** | \$0.60 | \$1.80 |
### Compute
**\$0.02 per minute** of active session time.
Compute time runs from session creation until termination or inactivity timeout. Sessions can run indefinitely while active, but expire after 5 minutes of inactivity by default. WebRun provisions real desktop environments with dedicated resources for each session, ensuring consistent browser behavior across all tasks.
### Proxy
| Proxy Mode | Cost |
| --------------------------- | ------------------------------ |
| **WebRun-managed** | \$4.00 per GB of data transfer |
| **Custom (bring your own)** | No additional charge |
WebRun-managed proxies route traffic through residential proxy pools with geographic targeting. Data transfer is measured across the entire session. Custom proxies incur no extra cost from WebRun; you pay your proxy provider directly.
See the [Proxies guide](/usage-guides/proxies) for configuration details.
Sessions remain billable until terminated. Set `terminateOnCompletion: true` on your final task or explicitly call terminate to avoid charges for the full timeout window.
***
## Usage Tracking
Every response includes a `usage` object with real-time cost tracking:
```json theme={null}
{
"success": true,
"sessionId": "abc123",
"taskId": "xyz789",
"type": "task_completed",
"data": {
"message": "Task completed successfully"
},
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"completion_time": 23.5,
"cost": 0.0124
}
}
```
View historical usage and costs at [app.webrun.ai/usage](https://app.webrun.ai/usage).
***
## Related
Reduce costs with best practices
Manage session lifecycle
Understanding polling and responses
All cost-related parameters
# Response Model
Source: https://docs.webrun.ai/concepts/response-model
Understanding WebRun's hybrid synchronous/asynchronous response model
## Synchronous vs Asynchronous
WebRun uses a **hybrid response model** that combines the simplicity of synchronous APIs with the reliability of asynchronous polling:
* **Tasks completing in \< 50 seconds:** Result returned inline (synchronous)
* **Tasks taking > 50 seconds:** Poll URL returned for async polling
This design eliminates unnecessary polling for the 90% of tasks that complete quickly, while gracefully handling longer operations.
***
## Why This Design?
Pure sync doesn't work because HTTP timeouts (30-60s) are too short for complex browser tasks. Pure async doesn't work because polling adds unnecessary complexity for simple tasks that finish in seconds.
The hybrid approach waits up to 50 seconds. If the task finishes in time, the result comes back inline. If not, you get a poll URL. In practice, \~90% of tasks return inline.
***
## How It Works
```
POST /start/run-task
↓
WebRun starts task
↓
Wait up to 50 seconds
↓
┌────────────────────────────────────┐
│ Did task complete in < 50s? │
│ │
│ YES → Return result inline │
│ NO → Return pollUrl │
└────────────────────────────────────┘
```
***
## Inline Response (\< 50 seconds)
When your task completes within 50 seconds, you get the full result in the initial response:
**Request:**
```bash theme={null}
POST /start/run-task
{
"prompt": "Search Google for Anthropic"
}
```
**Response:**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"type": "task_completed",
"data": {
"message": "Successfully searched for Anthropic on Google",
"files": [],
"network": [
{
"id": "tevo9",
"taskId": "x9y8z7w6v5u4",
"urls": [
{
"url": "https://www.google.com/search?q=Anthropic",
"timestamp": 1771138379087.646
}
]
}
]
},
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"completion_time": 23.5,
"cost": 0.0124
}
}
```
**Key indicator:** `type: "task_completed"`
***
## Pending Response (> 50 seconds)
For tasks that take longer than 50 seconds, you receive a `pollUrl` immediately:
**Request:**
```bash theme={null}
POST /start/run-task
{
"prompt": "Complete a complex multi-step workflow"
}
```
**Response (after 50 seconds):**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"status": "pending",
"pollUrl": "https://api.webrun.ai/task/a1b2c3d4e5f6/x9y8z7w6v5u4",
"message": "Task still running. Poll GET /task/:sessionId/:taskId for result."
}
```
**Key indicator:** `status: "pending"`
You must then poll the `pollUrl` until the task completes.
***
## Polling for Results
### Polling Endpoint
```
GET /task/:sessionId/:taskId
```
### Poll Until Completion
Poll every 2-3 seconds until you receive a final state:
**Still Running:**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"status": "running",
"usage": {
"prompt_tokens": 8000,
"completion_tokens": 2100,
"total_tokens": 10100,
"completion_time": 12.3,
"cost": 0.0067
}
}
```
**Completed:**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"type": "task_completed",
"data": {
"message": "Task finished successfully",
"files": [],
"network": [
{
"id": "abc12",
"taskId": "x9y8z7w6v5u4",
"urls": [
{
"url": "https://example.com/page",
"timestamp": 1771138379087.646
}
]
}
]
},
"usage": {
"prompt_tokens": 15420,
"completion_tokens": 4200,
"total_tokens": 19620,
"completion_time": 87.3,
"cost": 0.0187
}
}
```
**Guardrail Triggered:**
```json theme={null}
{
"success": true,
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "I need login credentials"
}
}
```
**Failed:**
```json theme={null}
{
"success": false,
"status": "failed",
"error": "Navigation timeout after 30 seconds",
"code": "NAVIGATION_TIMEOUT"
}
```
***
## Polling Best Practices
### 1. Poll Interval
Poll every 2-3 seconds. Faster polling wastes resources; slower polling adds unnecessary latency.
```javascript theme={null}
const POLL_INTERVAL = 2000; // 2 seconds
```
### 2. Maximum Attempts
Set a reasonable timeout (e.g., 2 minutes = 60 attempts at 2-second intervals):
```javascript theme={null}
const MAX_ATTEMPTS = 60;
```
### 3. Handle All Terminal States
Check for all possible completion states:
```javascript theme={null}
if (data.type === "task_completed") return data;
if (data.type === "guardrail_trigger") return data;
if (data.status === "failed") throw new Error(data.error);
if (data.status === "terminated") throw new Error("Session terminated");
```
### 4. Track Incremental Cost
The polling endpoint includes current cost in the `usage` object, allowing you to monitor spending in real-time.
***
## Complete Polling Implementation
```javascript theme={null}
async function pollForResult(sessionId, taskId, apiKey) {
const maxAttempts = 60; // 2 minutes
const interval = 2000; // 2 seconds
for (let i = 0; i < maxAttempts; i++) {
const res = await fetch(
`https://api.webrun.ai/task/${sessionId}/${taskId}`,
{ headers: { "Authorization": `Bearer ${apiKey}` } }
);
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
}
const data = await res.json();
// Terminal states
if (data.type === "task_completed") return data;
if (data.type === "guardrail_trigger") return data;
if (data.status === "failed") throw new Error(data.error || "Task failed");
if (data.status === "terminated") throw new Error("Session terminated");
// Still running
if (data.pending || data.status === "active") {
console.log(`Poll ${i + 1}/${maxAttempts}: Still running (cost so far: $${data.usage?.cost || 0})`);
await new Promise(r => setTimeout(r, interval));
continue;
}
// Unexpected state
return data;
}
throw new Error("Polling timeout after 2 minutes");
}
```
***
## Unified Request Handler
Handle both inline and pending responses with a single function:
```javascript theme={null}
async function runTask(prompt, apiKey) {
// Initial request
const response = await fetch("https://api.webrun.ai/start/run-task", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({ prompt })
});
const data = await response.json();
// Inline result
if (data.status === "complete") {
return data.result;
}
// Pending - start polling
if (data.status === "pending") {
return await pollForResult(data.sessionId, data.taskId, apiKey);
}
throw new Error(data.message || "Task failed");
}
// Usage
const result = await runTask("Search Google for Anthropic", "wr_xxx");
console.log(result.data.message);
```
***
## WebSocket Alternative
For real-time updates without polling, use WebSocket:
```javascript theme={null}
socket.on("message", (data) => {
if (data.type === "task_completed") {
console.log("Done:", data.data.message);
}
});
```
WebSocket removes the need for polling entirely by pushing updates as they occur.
[Learn more about WebSocket →](/integrations/websocket)
***
## Response Time Distribution
Based on typical usage patterns:
| Task Type | Typical Duration | Response Mode |
| --------------------- | ---------------- | ------------- |
| Simple search | 10-20s | Inline |
| Form filling | 20-40s | Inline |
| Multi-step navigation | 40-80s | Polling |
| Complex workflow | 80-180s | Polling |
**\~90% of tasks complete within 50 seconds and return inline.**
***
Full endpoint reference
Real-time alternative to polling
# Sessions
Source: https://docs.webrun.ai/concepts/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
}
}
```
***
Pause, resume, stop, and terminate sessions
Understanding task lifecycle and execution
Chain tasks effectively
Reduce costs with session management
Persist browser data and files across sessions
Route sessions through proxy servers
Runtime rules that control agent behavior
# Tasks
Source: https://docs.webrun.ai/concepts/tasks
Understanding browser tasks and their lifecycle
## What is a Task?
A **task** is a single objective for the AI agent to complete within a browser session. Each task is described in natural language and executed autonomously by the agent.
Examples of tasks:
* "Search Google for Anthropic and return the first result"
* "Find the price of the wireless keyboard on this page"
* "Fill out this form with the provided data and submit it"
* "Navigate through the checkout flow and screenshot the payment page"
* "Download the invoice from the billing portal and upload it to Google Drive"
***
## Task Lifecycle
Tasks progress through several states from initiation to completion:
```
┌─────────┐ ┌───────────┐ ┌─────────────────┐
│ Started │────►│ Running │────►│ task_completed │
└─────────┘ └───────────┘ └─────────────────┘
│
├───────────► guardrail_trigger
│
└───────────► failed
```
### Task States
| State | Description | What Happens |
| ------------------- | ------------------------------------ | --------------------------------- |
| `started` | Task has been accepted and queued | Agent prepares to execute |
| `running` | Agent is actively executing the task | Browser actions occurring |
| `task_completed` | Task finished successfully | Result available in response |
| `guardrail_trigger` | Agent needs human input to proceed | Task paused, awaiting response |
| `failed` | Task encountered an error | Session may continue or terminate |
***
## Task Patterns
There are two ways to execute tasks:
### Pattern 1: Single Task (`run-task`)
For one-off tasks where you don't need to maintain browser state. The session auto-terminates after completion.
```bash theme={null}
POST /start/run-task
{
"prompt": "Go to google.com and search for Anthropic"
}
```
### Pattern 2: Multi-Task Session
For workflows requiring sequential tasks within the same browser context (e.g., login → navigate → extract). The session persists across tasks, preserving cookies, authentication, and page state.
```bash theme={null}
# 1. Create session with initial task
POST /start/start-session
{
"task": {
"prompt": "Log into the dashboard",
"startingUrl": "https://example.com/login"
}
}
# 2. Send follow-up tasks to the session
POST /start/send-message
{
"sessionId": "sess_abc123",
"message": {
"actionType": "newTask",
"newState": "start",
"prompt": "Navigate to billing settings"
}
}
```
| Aspect | Single Task | Multi-Task Session |
| --------------------- | ---------------------- | ------------------------------------- |
| **Session lifecycle** | Auto-closes after task | Persists until terminated |
| **Use case** | Isolated, simple tasks | Multi-step workflows |
| **State sharing** | None | Cookies, auth, page context preserved |
For multi-task sessions, set `terminateOnCompletion: true` on your final task to avoid idle session charges.
***
## Task Properties
### Task Identification
Each task gets a unique `taskId` when created. Use this ID to:
* Poll for task status (REST API)
* Track specific tasks in multi-task workflows
* Retrieve task results
### Task Parameters
| Parameter | Type | Default | Description |
| ----------------------- | --------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `prompt` | string | required | Natural language task description |
| `maxDuration` | number | 300000 | Max time for this task in ms |
| `maxInputTokens` | number | 100000 | Max input tokens |
| `maxOutputTokens` | number | 100000 | Max output tokens |
| `startingUrl` | string | null | Starting URL (optional) |
| `terminateOnCompletion` | boolean | false | Auto-terminate session after this task |
| `secrets` | array | `[]` | Credentials for website authentication ([details](/usage-guides/secrets)) |
| `files` | string\[] | `[]` | File IDs to attach for upload tasks ([details](/environments/file-uploads)) |
| `environmentId` | string | null | Environment ID to attach to the session ([details](/environments/overview)). This is a top-level parameter, not nested inside the task. |
***
## Example: Complete Task Flow
Here's a practical example of sending a task and receiving the result:
**Request:**
```bash theme={null}
POST /start/run-task
Content-Type: application/json
{
"prompt": "Go to news.ycombinator.com and return the titles of the top 3 posts",
"maxDuration": 60000
}
```
**Response:**
```json theme={null}
{
"success": true,
"sessionId": "sess_7f8a9b2c",
"taskId": "task_3e4f5a6b",
"type": "task_completed",
"data": {
"message": "Here are the top 3 posts:\n1. Show HN: I built a new programming language\n2. The future of web browsers\n3. Why SQLite is so popular",
"files": [],
"network": [
{
"id": "hn001",
"taskId": "task_3e4f5a6b",
"urls": [
{
"url": "https://news.ycombinator.com/",
"timestamp": 1771138379087.646
}
]
}
]
},
"usage": {
"prompt_tokens": 8200,
"completion_tokens": 1500,
"total_tokens": 9700,
"completion_time": 15.2,
"cost": 0.0072
}
}
```
***
## Task Results
When a task completes successfully, you receive a structured result:
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"type": "task_completed",
"data": {
"message": "Successfully completed the search",
"files": [
{
"source": "https://example.com/report.zip",
"downloadUrl": "https://blobs.webrun.ai/files/report.zip",
"filename": "report.zip",
"timestamp": 1771138379108
}
],
"network": [
{
"id": "tevo9",
"taskId": "x9y8z7w6v5u4",
"urls": [
{
"url": "https://example.com/api/data",
"timestamp": 1771138379087.646
}
]
}
]
},
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"completion_time": 23.5,
"cost": 0.0124
},
"completedAt": "2024-01-15T10:30:00Z"
}
```
### Result Fields
| Field | Description |
| -------------------------- | ------------------------------------------------------------------- |
| `data.message` | Natural language result from the agent |
| `data.files` | Array of files downloaded during task execution (optional) |
| `data.files[].source` | Original URL the file was downloaded from |
| `data.files[].downloadUrl` | WebRun-hosted URL to download the file |
| `data.files[].filename` | Name of the downloaded file |
| `data.files[].timestamp` | Unix timestamp (ms) when the file was downloaded |
| `data.network` | Array of network requests captured during task execution (optional) |
| `data.network[].id` | Unique identifier for the network entry |
| `data.network[].taskId` | Task that generated the network activity |
| `data.network[].urls` | Array of URLs requested with timestamps |
| `usage.prompt_tokens` | Input tokens used |
| `usage.completion_tokens` | Output tokens generated |
| `usage.total_tokens` | Sum of input and output tokens |
| `usage.completion_time` | Time taken to complete task (seconds) |
| `usage.cost` | Total cost in USD |
| `completedAt` | ISO 8601 timestamp |
***
## Task Execution
### Sequential Execution
Within a single session, tasks run sequentially:
```
Session: sess_abc
├── Task 1 (running) → completes
├── Task 2 (queued) → starts → completes
└── Task 3 (queued) → starts → completes
```
You cannot run multiple tasks in parallel within the same session. For concurrent execution, use multiple sessions.
### Task Duration
Most tasks complete in 10-40 seconds. The API waits up to 50 seconds before returning a `pollUrl` for longer tasks.
**Typical completion times:**
* Simple search/navigation: 10-20 seconds
* Form filling: 20-40 seconds
* Complex multi-step: 60-120 seconds
### Task Dependencies
Tasks can build on previous state within a session. Use the `send-message` endpoint to add tasks to an existing session:
```bash theme={null}
POST /start/send-message
Content-Type: application/json
{
"sessionId": "sess_abc123",
"message": {
"actionType": "newTask",
"newState": "start",
"prompt": "Go to my account settings and extract my email address",
"terminateOnCompletion": true
}
}
```
This is useful for multi-step workflows where each task depends on the previous one:
1. **Task 1:** Log into the website → session now authenticated
2. **Task 2:** Navigate to settings → page context preserved
3. **Task 3:** Extract data → has access to authenticated page
***
## Writing Effective Task Descriptions
### Be Specific
Bad: "Find products"
Good: "Search Amazon for wireless keyboards under \$50 and return the top 3 results with prices"
### Include Context
Bad: "Click the button"
Good: "Click the blue 'Add to Cart' button next to the first product"
### Specify Output Format
Bad: "Get the data"
Good: "Extract the product name, price, and rating as a JSON object"
### Break Down Complex Tasks
Bad: "Research this company and create a report"
Good:
1. "Search Google for \[company name] and find their website"
2. "Navigate to their About page and extract the company description"
3. "Find their contact information and return it in structured format"
***
## Task Constraints
### Maximum Duration
Tasks can have a `maxDuration` limit specifying the maximum execution time (default and max: 5 minutes). Session inactivity timeout is separate and fixed at 5 minutes.
### Token Limits
Tasks are constrained by `maxInputTokens` and `maxOutputTokens`. If limits are exceeded:
* Input limit: Task fails with error
* Output limit: Agent's response is truncated
### Domain Restrictions
Use [automation policies](/concepts/policies) with domain rules to control which websites the agent can visit. When a domain is blocked by policy, the agent will:
* Refuse to navigate to those domains
* Trigger a guardrail if configured to do so
* Skip links to those domains in search results
***
## Common Task Patterns
### Research & Extraction
"Search for \[topic] and return \[specific data]"
### Navigation & Screenshot
"Go to \[URL] and take a screenshot of \[element]"
### Form Filling
"Fill out the form with: Name=\[value], Email=\[value], then submit"
### Verification
"Check if \[condition] is true on \[page]"
### File Downloads & Uploads
"Download the CSV report from \[site A] and upload it to \[site B]"
### Conditional Actions
"If \[condition], then \[action], otherwise \[alternative action]"
***
## Related
How to create and send tasks
Poll for task results
When tasks need human input
Get structured data from tasks
Persist browser data and files across sessions
Upload files for the agent to use in sessions
# Environments API
Source: https://docs.webrun.ai/environments/environments-api
Create, list, and delete environments; upload browser profiles and manage attached files
Manage environments programmatically. These endpoints let you create and delete environments, upload browser profile data, and manage files attached to an environment.
## Authentication
All endpoints require an API key in the `Authorization` header:
```bash theme={null}
Authorization: Bearer
```
## Base URL
```
https://api.webrun.ai
```
***
## Create an Environment
```
POST /environments
Content-Type: application/json
```
| Field | Type | Required | Description |
| ------------- | ------ | -------- | -------------------- |
| `name` | string | Yes | Environment name |
| `description` | string | No | Optional description |
```bash theme={null}
curl -X POST https://api.webrun.ai/environments \
-H "Authorization: Bearer wr_xxx" \
-H "Content-Type: application/json" \
-d '{"name": "my-environment", "description": "optional description"}'
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Environment created",
"environment": {
"_id": "",
"userId": "67f1a2b3c4d5e6f7a8b9c0d1",
"name": "my-environment",
"description": "optional description",
"status": "empty",
"createdAt": "2026-02-09T12:00:00.000Z",
"updatedAt": "2026-02-09T12:00:00.000Z"
}
}
```
### Errors
| Status | Message | Cause |
| ------ | ---------------------------------- | -------------------------------- |
| 400 | Environment name is required | Missing or empty `name` field |
| 400 | Maximum of 20 environments allowed | User already has 20 environments |
***
## List Environments
Returns all environments for the authenticated user.
```
GET /environments
```
```bash theme={null}
curl https://api.webrun.ai/environments \
-H "Authorization: Bearer wr_xxx"
```
**Response:**
```json theme={null}
{
"success": true,
"environments": [
{
"_id": "",
"userId": "67f1a2b3c4d5e6f7a8b9c0d1",
"name": "my-environment",
"description": "optional description",
"status": "ready",
"createdAt": "2026-02-09T12:00:00.000Z",
"updatedAt": "2026-02-09T12:30:00.000Z"
}
]
}
```
### Response Fields
| Field | Type | Description |
| ------------- | ------ | -------------------------------- |
| `_id` | string | Unique environment identifier |
| `userId` | string | Owner's user ID |
| `name` | string | Environment name |
| `description` | string | Environment description |
| `status` | string | `empty`, `uploading`, or `ready` |
| `createdAt` | string | ISO 8601 creation timestamp |
| `updatedAt` | string | ISO 8601 last update timestamp |
***
## Delete an Environment
Permanently deletes an environment, its browser profile data, and all attached files.
```
DELETE /environments/
```
```bash theme={null}
curl -X DELETE https://api.webrun.ai/environments/ \
-H "Authorization: Bearer wr_xxx"
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Environment deleted"
}
```
### Errors
| Status | Message | Cause |
| ------ | --------------------- | ------------------------------------------------- |
| 404 | Environment not found | Invalid ID or environment belongs to another user |
***
## Upload Browser Profile Data
Uploads a `.tar.gz` Chrome profile archive to an environment. Replaces any existing profile data and sets the status to `ready`.
```
POST /environments//upload
Content-Type: multipart/form-data
```
| Parameter | Location | Description |
| --------- | ---------- | -------------------------------------- |
| `ENV_ID` | URL path | The environment ID |
| `file` | Form field | `.tar.gz` profile archive (max 500 MB) |
```bash theme={null}
curl -X POST https://api.webrun.ai/environments//upload \
-H "Authorization: Bearer wr_xxx" \
-F "file=@/path/to/profile.tar.gz"
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Profile uploaded successfully",
"environment": {
"_id": "",
"name": "my-environment",
"status": "ready",
"blobSize": 4521984,
"blobUploadedAt": "2026-02-09T12:30:00.000Z"
}
}
```
### Errors
| Status | Message | Cause |
| ------ | ------------------------------ | ------------------------------------------------- |
| 400 | No file provided | Missing `file` field in form data |
| 400 | Only .tar.gz files are allowed | File is not a valid `.tar.gz` archive |
| 404 | Environment not found | Invalid ID or environment belongs to another user |
To upload your local Chrome profile instead of a manual archive, use the [sync tool](/environments/profiles#sync-from-local-chrome); it packages and uploads your browser data in one command.
***
## List Files in an Environment
Returns all files attached to an environment.
```
GET /environments//files
```
```bash theme={null}
curl https://api.webrun.ai/environments//files \
-H "Authorization: Bearer wr_xxx"
```
**Response:**
```json theme={null}
{
"success": true,
"files": [
{
"fileId": "abc123...",
"originalName": "sample.zip",
"size": 204800,
"createdAt": "2026-02-09T12:00:00.000Z"
}
]
}
```
### Response Fields
| Field | Type | Description |
| -------------- | ------ | ----------------------------- |
| `fileId` | string | Unique file identifier |
| `originalName` | string | Original filename as uploaded |
| `size` | number | File size in bytes |
| `createdAt` | string | ISO 8601 upload timestamp |
***
## Delete a File from an Environment
Permanently removes a specific file from an environment.
```
DELETE /environments//files/
```
```bash theme={null}
curl -X DELETE https://api.webrun.ai/environments//files/ \
-H "Authorization: Bearer wr_xxx"
```
**Response:**
```json theme={null}
{
"success": true,
"message": "File deleted"
}
```
### Errors
| Status | Message | Cause |
| ------ | -------------- | ----------------------------------------------------------- |
| 404 | File not found | Invalid file ID or file does not belong to this environment |
***
## Common Errors
All error responses follow this format:
```json theme={null}
{
"success": false,
"message": "Description of the error"
}
```
| Status | Message | Cause |
| ------ | -------------------------- | ---------------------------------------- |
| 401 | API key required | Missing `Authorization` header |
| 401 | Invalid or revoked API key | API key is incorrect or has been revoked |
| 403 | Account is deactivated | User account is disabled |
| 500 | Authentication error | Server-side authentication failure |
***
What environments are and when to use them
Schedule recurring tasks under an environment
Upload files for use in sessions
How browser profiles work, sync from local Chrome
# File Uploads
Source: https://docs.webrun.ai/environments/file-uploads
Upload files to environments for persistent access, or upload standalone files for temporary use
When your agent needs to work with files (submitting a PDF to a form, importing a spreadsheet, or uploading an image) you upload them first and then reference them by `fileId` in your tasks.
Files can be uploaded in two modes:
| Mode | Behavior |
| -------------- | ----------------------------------------------------------------------------------------------------------------------- |
| **Persistent** | Attached to an environment. Available to any session on that environment. Only deleted when you explicitly remove them. |
| **Orphan** | No environment attached. Automatically deleted after **1 hour**. Can be promoted to an environment later. |
***
## Upload to an Environment (Persistent)
Include `environmentId` in the form data to attach the file permanently to an environment. Any session using that environment can access the file at any time.
```bash theme={null}
curl -X POST https://api.webrun.ai/files/upload \
-H "Authorization: Bearer wr_xxx" \
-F "files=@/path/to/sample.zip" \
-F "environmentId="
```
**Response:**
```json theme={null}
{
"success": true,
"files": [
{
"fileId": "abc123...",
"originalName": "sample.zip",
"size": 204800
}
]
}
```
***
## Upload Without an Environment (Orphan)
Omit `environmentId` to upload a standalone file. It is automatically deleted after 1 hour unless promoted to an environment.
```bash theme={null}
curl -X POST https://api.webrun.ai/files/upload \
-H "Authorization: Bearer wr_xxx" \
-F "files=@/path/to/sample.zip"
```
An orphan file is automatically promoted to an environment when you pass its `fileId` in a session or task that also includes an `environmentId`. Once the session runs, the file is persisted to that environment and won't expire.
***
## Upload Response Fields
| Field | Type | Description |
| ---------------------- | ------- | ---------------------------------------------------------- |
| `success` | boolean | Whether the upload succeeded |
| `files` | array | Array of uploaded file metadata |
| `files[].fileId` | string | Unique identifier: use this to reference the file in tasks |
| `files[].originalName` | string | Original filename as uploaded |
| `files[].size` | number | File size in bytes |
***
## Uploading Multiple Files
Repeat the `files` field to upload several files in one request:
```bash theme={null}
curl -X POST https://api.webrun.ai/files/upload \
-H "Authorization: Bearer wr_xxx" \
-F "files=@document.pdf" \
-F "files=@photo.png" \
-F "files=@spreadsheet.xlsx" \
-F "environmentId="
```
***
## Using Files in a Session
Reference uploaded files by `fileId` when starting a task. Pass them in the `files` array alongside `environmentId` to use the environment's browser profile and persist orphan files at the same time.
### With /start/run-task
```bash theme={null}
curl -X POST https://api.webrun.ai/start/run-task \
-H "Authorization: Bearer wr_xxx" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Open the uploaded spreadsheet and extract the data",
"environmentId": "",
"files": [""]
}'
```
### With /start/start-session
Include `files` inside the `task` object:
```json theme={null}
{
"mode": "default",
"environmentId": "",
"task": {
"prompt": "Process the attached report",
"startingUrl": "https://example.com/dashboard",
"files": ["abc123..."]
}
}
```
### With /start/send-message
Include `files` in the `message` object when sending a `newTask` action:
```json theme={null}
{
"sessionId": "a1b2c3d4e5f6",
"message": {
"actionType": "newTask",
"newState": "start",
"prompt": "Upload the attached spreadsheet to the data import page",
"startingUrl": "https://example.com/import",
"files": ["ghi789..."]
}
}
```
***
## Complete Example
Upload an orphan file, then run a task with an environment; the file gets persisted automatically:
```javascript theme={null}
const API_KEY = process.env.WEBRUN_API_KEY;
const ENV_ID = "";
// Step 1: Upload the file (orphan, no environmentId yet)
const formData = new FormData();
formData.append("files", fs.createReadStream("report.pdf"));
const uploadResponse = await fetch("https://api.webrun.ai/files/upload", {
method: "POST",
headers: { "Authorization": `Bearer ${API_KEY}` },
body: formData
}).then(r => r.json());
const fileId = uploadResponse.files[0].fileId;
// Step 2: Run a task with the environment and file
// The orphan file is promoted to the environment automatically
const taskResponse = await fetch("https://api.webrun.ai/start/run-task", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
prompt: "Go to the upload page and submit the attached PDF report",
startingUrl: "https://example.com/submit",
environmentId: ENV_ID,
files: [fileId]
})
}).then(r => r.json());
console.log(taskResponse);
```
***
## Managing Environment Files
List or delete files attached to an environment using the [Environments API](/environments/environments-api):
```bash theme={null}
# List all files in an environment
curl https://api.webrun.ai/environments//files \
-H "Authorization: Bearer wr_xxx"
# Delete a specific file
curl -X DELETE https://api.webrun.ai/environments//files/ \
-H "Authorization: Bearer wr_xxx"
```
***
## Endpoint Reference
| Endpoint | Field | Location |
| ----------------------------------------------- | ------------------- | -------------------------------------------- |
| `POST /files/upload` | `files` (multipart) | Form data |
| `POST /files/upload` | `environmentId` | Form data (optional: omit for orphan upload) |
| `POST /start/run-task` | `files` | Request body |
| `POST /start/run-task` | `environmentId` | Request body |
| `POST /start/start-session` | `files` | Inside `task` object |
| `POST /start/send-message` | `files` | Inside `message` object |
| `GET /environments//files` | — | List files in an environment |
| `DELETE /environments//files/` | — | Delete a file from an environment |
***
Create environments and manage attached files
What environments are and when to use them
Provide credentials for authenticated sessions
Get notified when tasks complete
# Environments
Source: https://docs.webrun.ai/environments/overview
Bundle a browser profile and persistent file storage into a reusable container for your automation sessions
An environment is a named container that bundles a **browser profile** (cookies, local storage, extensions, cached credentials), **persistent file storage**, and optional **triggers** for scheduled automation. Pass `environmentId` when starting a session and it loads that browser state and makes those files available: no re-authentication, no re-uploading.
***
## Why Environments Matter
| Without an environment | With an environment |
| ------------------------------------------ | ------------------------------------------------------- |
| Every session starts from a blank browser | Sessions inherit saved login state and site preferences |
| You log in every time | Log in once, reuse across all future sessions |
| Files must be uploaded on every run | Files persist and are available to any session |
| No shared state between tasks | Browser data and files carry over until you delete them |
| Recurring tasks require your own scheduler | Triggers run automatically on a schedule you define |
***
## What's Inside
### Browser Profile
Stores Chrome data (cookies, local storage, IndexedDB, extensions, cached credentials) and carries it from one session to the next. Log in once and every subsequent session on the same environment skips authentication.
See [Browser Profiles](/environments/profiles) for details on how profiles work, including how to [sync from your local Chrome](/environments/profiles#sync-from-local-chrome).
### File Storage
Files attached to an environment stay until you explicitly delete them. Any session running under that environment can access those files without re-uploading. Useful for reference documents, configuration files, templates, or any asset your automation uses repeatedly.
See [File Uploads](/environments/file-uploads) for persistent and temporary upload modes.
### Triggers
Schedule browser automation tasks that run automatically on a recurring basis under this environment. Each trigger inherits the environment's browser profile and files, so scheduled tasks can access logged-in sessions and stored data without extra setup. Results are delivered via webhook, bot notification, or both.
See [Triggers](/environments/triggers) for schedule types, delivery modes, and the full API reference.
***
## Lifecycle
```
Create → Upload profile data (optional) → Upload files (optional) → Use in sessions → Delete
```
1. **Create** an environment with a name and optional description.
2. **Upload** browser profile data (`.tar.gz`) if you have existing state to restore, or [sync](/environments/profiles#sync-from-local-chrome) from your local Chrome.
3. **Upload** any files sessions need to access.
4. **Use** the environment by passing `environmentId` when starting a session or task. The session loads the profile and has access to all stored files.
5. **Delete** when no longer needed. This removes the profile and all attached files.
***
## Quick Example
Create an environment, then run a task with it:
```bash theme={null}
# Create the environment
curl -X POST https://api.webrun.ai/environments \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "my-environment"}'
# Use it in a task
curl -X POST https://api.webrun.ai/start/run-task \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Go to my dashboard and export the monthly report",
"environmentId": ""
}'
```
***
## Limits
| Resource | Limit |
| --------------------------- | ----------------- |
| Environments per user | 20 |
| Browser profile upload size | 500 MB |
| Accepted profile format | `.tar.gz`, `.tgz` |
***
## Next Steps
Create, list, and delete environments; upload profiles and manage files
Schedule recurring browser automation tasks under an environment
How browser profiles work, sync from local Chrome
Persistent and temporary file upload modes
# Profile Management API
Source: https://docs.webrun.ai/environments/profile-management-api
Upload, download, and manage browser profile data stored in environments
These endpoints operate on browser profile data stored within environments. They use the `/profiles` path and provide operations like **downloading** profile archives that complement the [Environments API](/environments/environments-api).
To create, list, or delete environments, use the [Environments API](/environments/environments-api). The endpoints below focus on managing the browser profile data inside an environment.
## Authentication
All endpoints require an API key with `task:create` permission:
```bash theme={null}
Authorization: Bearer
```
## Base URL
```
https://api.webrun.ai
```
***
## List Profiles
Returns all environments with their profile metadata, sorted by newest first. This is equivalent to listing environments but includes additional profile-specific fields like `blobSize`, `lastUsedAt`, and `usageCount`.
```
GET /profiles
```
```bash theme={null}
curl https://api.webrun.ai/profiles \
-H "Authorization: Bearer wr_abc123..."
```
**Response:**
```json theme={null}
{
"success": true,
"profiles": [
{
"_id": "683a1f2e4b0c1d2e3f4a5b6c",
"userId": "67f1a2b3c4d5e6f7a8b9c0d1",
"name": "My Shopping Profile",
"description": "Amazon and eBay sessions",
"blobSize": 4521984,
"blobUploadedAt": "2026-02-08T14:30:00.000Z",
"lastUsedAt": "2026-02-09T10:15:00.000Z",
"usageCount": 12,
"status": "ready",
"createdAt": "2026-02-01T09:00:00.000Z",
"updatedAt": "2026-02-09T10:15:00.000Z"
}
]
}
```
### Response Fields
| Field | Type | Description |
| ---------------- | ------ | --------------------------------------------------- |
| `_id` | string | Environment identifier (same as the environment ID) |
| `name` | string | Environment name |
| `description` | string | Environment description |
| `blobSize` | number | Size of profile data in bytes |
| `blobUploadedAt` | string | ISO 8601 timestamp of last profile upload |
| `lastUsedAt` | string | ISO 8601 timestamp of last session usage |
| `usageCount` | number | Number of times used in sessions |
| `status` | string | `empty`, `uploading`, or `ready` |
| `createdAt` | string | ISO 8601 creation timestamp |
| `updatedAt` | string | ISO 8601 last update timestamp |
***
## Create Profile
Creates a new environment with an empty browser profile. You can populate it by [uploading data](#upload-profile-data), [syncing from your local machine](/environments/sync-profiles), or by running a session with the environment attached.
```
POST /profiles
Content-Type: application/json
```
| Field | Type | Required | Description |
| ------------- | ------ | -------- | ------------------------------------- |
| `name` | string | Yes | Environment name (max 100 characters) |
| `description` | string | No | Description (max 500 characters) |
```bash theme={null}
curl -X POST https://api.webrun.ai/profiles \
-H "Authorization: Bearer wr_abc123..." \
-H "Content-Type: application/json" \
-d '{"name": "My Profile", "description": "For social media automation"}'
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Profile created",
"profile": {
"_id": "683a1f2e4b0c1d2e3f4a5b6c",
"userId": "67f1a2b3c4d5e6f7a8b9c0d1",
"name": "My Profile",
"description": "For social media automation",
"blobSize": 0,
"status": "empty",
"usageCount": 0,
"createdAt": "2026-02-09T12:00:00.000Z",
"updatedAt": "2026-02-09T12:00:00.000Z"
}
}
```
### Errors
| Status | Message | Cause |
| ------ | ------------------------------ | -------------------------------- |
| 400 | Profile name is required | Missing or empty `name` field |
| 400 | Maximum of 20 profiles allowed | User already has 20 environments |
***
## Delete Profile
Permanently deletes an environment and all its stored data (profile and files).
```
DELETE /profiles/:id
```
| Parameter | Location | Description |
| --------- | -------- | ------------------ |
| `id` | URL path | The environment ID |
```bash theme={null}
curl -X DELETE https://api.webrun.ai/profiles/683a1f2e4b0c1d2e3f4a5b6c \
-H "Authorization: Bearer wr_abc123..."
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Profile deleted"
}
```
### Errors
| Status | Message | Cause |
| ------ | ----------------- | ------------------------------------------------- |
| 404 | Profile not found | Invalid ID or environment belongs to another user |
***
## Download Profile Data
Returns a temporary signed URL to download the browser profile as a `.tar.gz` archive. The URL expires after **1 hour**.
```
GET /profiles/:id/download
```
| Parameter | Location | Description |
| --------- | -------- | ------------------ |
| `id` | URL path | The environment ID |
```bash theme={null}
curl https://api.webrun.ai/profiles/683a1f2e4b0c1d2e3f4a5b6c/download \
-H "Authorization: Bearer wr_abc123..."
```
**Response:**
```json theme={null}
{
"success": true,
"downloadUrl": "https://storage.example.com/profiles/683a1f2e4b0c1d2e3f4a5b6c.tar.gz?token=eyJhbGciOi..."
}
```
Use the returned URL to download the file:
```bash theme={null}
curl -o profile-backup.tar.gz ""
```
### Errors
| Status | Message | Cause |
| ------ | ------------------------------- | ----------------------------------------------------- |
| 400 | Profile has no data to download | Profile status is not `ready` or has no uploaded data |
| 404 | Profile not found | Invalid ID or environment belongs to another user |
***
## Upload Profile Data
Uploads browser profile data as a `.tar.gz` archive to an environment. Replaces any existing profile data and sets the status to `ready`.
```
POST /profiles/:id/upload
Content-Type: multipart/form-data
```
| Parameter | Location | Description |
| --------- | ---------- | --------------------------- |
| `id` | URL path | The environment ID |
| `file` | Form field | `.tar.gz` file (max 500 MB) |
```bash theme={null}
curl -X POST https://api.webrun.ai/profiles/683a1f2e4b0c1d2e3f4a5b6c/upload \
-H "Authorization: Bearer wr_abc123..." \
-F "file=@my-profile.tar.gz"
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Profile uploaded successfully",
"profile": {
"_id": "683a1f2e4b0c1d2e3f4a5b6c",
"name": "My Profile",
"status": "ready",
"blobSize": 4521984,
"blobUploadedAt": "2026-02-09T12:30:00.000Z"
}
}
```
### Errors
| Status | Message | Cause |
| ------ | ------------------------------ | ------------------------------------------------- |
| 400 | No file provided | Missing `file` field in form data |
| 400 | Only .tar.gz files are allowed | File is not a valid `.tar.gz` archive |
| 404 | Profile not found | Invalid ID or environment belongs to another user |
You can also upload profile data via the [Environments API](/environments/environments-api#upload-browser-profile-data) at `POST /environments//upload`. Both endpoints produce the same result.
***
## Rate Limits
Profile endpoints share the global rate limit of **100 requests per 15 minutes per IP**.
***
## Common Errors
All error responses follow this format:
```json theme={null}
{
"success": false,
"message": "Description of the error"
}
```
| Status | Message | Cause |
| ------ | ------------------------------------------------ | ------------------------------------------ |
| 401 | API key required | Missing `Authorization` header |
| 401 | Invalid or revoked API key | API key is incorrect or has been revoked |
| 403 | Account is deactivated | User account is disabled |
| 403 | API key missing required permission: task:create | API key lacks the `task:create` permission |
| 500 | Authentication error | Server-side authentication failure |
***
How browser profiles work within environments
Create, list, and delete environments; manage files
Upload your local Chrome profile with one command
# Browser Profiles
Source: https://docs.webrun.ai/environments/profiles
Persist cookies, local storage, and browser state across sessions using an environment's browser profile
Every environment includes a browser profile that stores persistent Chrome data: cookies, local storage, extensions, IndexedDB, cached credentials. When you attach an environment to a session, the browser starts with that saved state already loaded.
**Without a profile:** every session opens a blank browser. You log in each time, re-accept cookie banners, and lose any site-specific data.
**With a profile:** sessions pick up where you left off. Login cookies persist, preferences carry over, and previously saved data is available immediately.
***
## Use Cases
### Skip Repeated Logins
Log in once, then reuse that session state across future tasks:
1. Create an environment and run a session with it attached
2. Log in to the target site during the session
3. The profile saves your login cookies automatically when the session ends
4. Future sessions on the same environment start already authenticated
### Preserve Site Preferences
Cookie consent choices, language settings, dark mode preferences, and other site-specific configuration carry over between sessions without any extra setup.
### Maintain Application State
For e-commerce or SaaS workflows, keep cart contents, workspace configurations, or application state intact between sessions.
***
## Profile Status
Each environment tracks the state of its browser profile:
| Status | Meaning |
| ----------- | ----------------------------------------------------------------------------------------- |
| `empty` | No browser data yet. Sessions start with a clean browser and populate the profile on exit |
| `uploading` | A profile upload is in progress |
| `ready` | Has browser data. Sessions load the saved state before executing tasks |
You can attach an environment with status `empty` to a session. The session starts with a clean browser, and the profile is populated automatically when the session ends.
***
## Populating a Profile
There are three ways to get browser data into an environment's profile:
| Method | When to use |
| -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| **Run a session** | Easiest: just run a session with the environment attached, log in, and the profile saves automatically |
| **[Sync from local Chrome](#sync-from-local-chrome)** | You're already logged into sites locally and want to transfer that state |
| **[Upload a `.tar.gz` archive](/environments/environments-api#upload-browser-profile-data)** | You have an exported Chrome profile archive to restore |
***
## Using a Profile in a Session
Pass `environmentId` when starting a session or task. The browser loads the profile's saved data before executing anything:
```bash theme={null}
curl -X POST https://api.webrun.ai/start/run-task \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"environmentId": "",
"prompt": "Go to amazon.com and check my order status"
}'
```
After the session ends, any changes to the browser state (new cookies, updated local storage) are saved back to the profile automatically.
***
## Sync from Local Chrome
The sync command packages your local Chrome browser data and uploads it directly to an environment. This is the fastest way to populate a profile if you're already logged into sites locally.
### Sync to an Existing Environment
If you've already [created an environment](/environments/environments-api#create-an-environment), sync your local browser data to it:
```bash theme={null}
bash <(curl -fsSL https://webrun.ai/sync/sync.sh) --environmentId --key
```
| Parameter | Description |
| ----------------- | ------------------------------------ |
| `--environmentId` | The ID of the environment to sync to |
| `--key` | Your WebRun API key |
This replaces any existing profile data in the environment. The status changes to `ready` once the upload completes.
### Create and Sync in One Step
To create a new environment and upload your local data in a single command, omit `--environmentId`:
```bash theme={null}
bash <(curl -fsSL https://webrun.ai/sync/sync.sh) --key
```
This creates a new environment, uploads your Chrome profile, and returns the new environment ID.
Save the environment ID returned by the command. You'll need it to pass as `environmentId` when starting sessions.
***
## Limits
| Resource | Limit |
| --------------------- | ----------------- |
| Environments per user | 20 |
| Profile upload size | 500 MB |
| Accepted format | `.tar.gz`, `.tgz` |
***
What environments are and when to use them
Create environments and upload profile data via the API
# Triggers
Source: https://docs.webrun.ai/environments/triggers
Schedule recurring browser automation tasks that run on a defined cadence under an environment
Triggers let you schedule browser automation tasks that execute automatically on a recurring basis. Each trigger is tied to an [environment](/environments/overview), so it inherits the browser profile, stored cookies, and persistent files: no re-authentication required between runs.
***
## Why Triggers
| Without triggers | With triggers |
| ------------------------------------------------ | -------------------------------------------------------------------- |
| You trigger every task manually via API call | Tasks run automatically on your chosen schedule |
| You build and maintain your own scheduler | Scheduling, retries, and failure handling are built in |
| Missed runs require manual intervention | The system tracks run history and pauses after repeated failures |
| Webhook delivery requires custom wiring per task | Delivery mode (webhook, bot, or both) is configured once per trigger |
***
## How It Works
1. **Create** a trigger linked to an environment, with a schedule and task details.
2. **The system executes** your task at each scheduled time using the environment's browser profile and files.
3. **Results are delivered** via webhook, bot notification, or both, depending on your `deliveryMode` setting.
4. **Run history** is recorded for every execution so you can audit outcomes and debug failures.
```
Create trigger → System runs on schedule → Results delivered → Run history logged
```
***
## Schedule Types
Every trigger requires a `scheduleType` that determines when and how often it runs.
| Type | Field | Description | Example |
| ------- | ------------------ | ---------------------------------------------------- | ---------------------------------- |
| `at` | `scheduleAt` | Run once at a specific date/time (ISO 8601) | `"2026-03-01T09:00:00Z"` |
| `every` | `scheduleInterval` | Run at a fixed interval | `"30m"`, `"2h"`, `"1d"` |
| `cron` | `scheduleCron` | Standard cron expression for full scheduling control | `"0 9 * * 1-5"` (weekdays at 9 AM) |
All schedules respect the `timezone` field (defaults to `UTC`).
Use `scheduleType: "cron"` with a standard cron expression for maximum flexibility; for example, `"0 */6 * * *"` runs every 6 hours, and `"30 8 1 * *"` runs at 8:30 AM on the first of each month.
***
## Delivery Modes
Control how run results are delivered using the `deliveryMode` field.
| Mode | Description |
| --------- | ---------------------------------------------------- |
| `webhook` | Results are sent to your configured webhook endpoint |
| `bot` | Results are delivered via bot notification |
| `both` | Results are sent to both webhook and bot |
When `deliveryMode` is `webhook` or `both`, you must provide a `webhook` configuration object. See [Webhooks](/usage-guides/webhooks) for details on webhook parameters.
***
## Automation Policy
Triggers can optionally be associated with an [automation policy](/concepts/policies). Policies define rules that govern agent behavior during execution, such as domain restrictions, blocked keywords, action type controls, and capability limits.
When a policy is assigned, the browser agent will enforce those rules for every run of the trigger. This is useful for compliance, safety guardrails, or scoping what the agent is allowed to do.
To assign a policy, pass the `policyId` field when creating or updating a trigger, or select one from the "Automation Policy" dropdown in the dashboard.
***
## Trigger Statuses
| Status | Meaning |
| -------- | ---------------------------------------------------- |
| `active` | Trigger is running on schedule |
| `paused` | Trigger is paused and will not execute until resumed |
A trigger is automatically paused after reaching `maxConsecutiveFailures` (default: 5). Resume it with the [resume endpoint](#resume-a-trigger) after resolving the issue.
***
## Authentication
All endpoints require an API key in the `Authorization` header:
```bash theme={null}
Authorization: Bearer
```
## Base URL
```
https://api.webrun.ai
```
***
## List Triggers
Returns all triggers for the authenticated user, sorted by creation date (newest first).
```
GET /cron-jobs
```
```bash theme={null}
curl https://api.webrun.ai/cron-jobs \
-H "Authorization: Bearer wr_xxx"
```
**Response:**
```json theme={null}
{
"success": true,
"cronJobs": [
{
"_id": "664a1b2c3d4e5f6a7b8c9d0e",
"userId": "67f1a2b3c4d5e6f7a8b9c0d1",
"environmentId": "683a1f2e4b0c1d2e3f4a5b6c",
"policyId": null,
"name": "Daily price check",
"description": "Check competitor prices every morning",
"scheduleType": "cron",
"scheduleCron": "0 9 * * *",
"timezone": "America/New_York",
"prompt": "Go to competitor.com/pricing and extract all plan prices",
"outputType": "structured",
"deliveryMode": "webhook",
"status": "active",
"nextRunAt": "2026-02-25T14:00:00.000Z",
"consecutiveFailures": 0,
"createdAt": "2026-02-20T10:00:00.000Z"
}
]
}
```
***
## Create a Trigger
```
POST /cron-jobs
Content-Type: application/json
```
### Request Body
| Field | Type | Required | Description |
| ------------------------ | ------ | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | string | Yes | Trigger name |
| `description` | string | No | Optional description |
| `environmentId` | string | Yes | ID of the [environment](/environments/overview) to use |
| `scheduleType` | string | Yes | `"at"`, `"every"`, or `"cron"` |
| `scheduleAt` | string | Conditional | ISO 8601 datetime (required when `scheduleType` is `"at"`) |
| `scheduleInterval` | string | Conditional | Interval string like `"30m"`, `"2h"` (required when `scheduleType` is `"every"`) |
| `scheduleCron` | string | Conditional | Cron expression (required when `scheduleType` is `"cron"`) |
| `timezone` | string | No | IANA timezone (default: `"UTC"`) |
| `prompt` | string | Yes | Instructions for the browser automation task |
| `startingUrl` | string | No | URL where the task should begin |
| `outputType` | string | No | `"text"` (default) or `"structured"` |
| `outputSchema` | object | No | JSON Schema for structured output (when `outputType` is `"structured"`) |
| `deliveryMode` | string | No | `"webhook"`, `"bot"`, or `"both"` (default: `"webhook"`) |
| `webhook` | object | Conditional | Webhook config (required when `deliveryMode` includes `"webhook"`) |
| `retryPolicy` | object | No | Custom retry configuration |
| `policyId` | string | No | ID of an [automation policy](/concepts/policies) to apply to this trigger's executions. When set, the browser agent will follow the policy's rules (domain restrictions, keyword blocking, capability controls, etc.) |
| `maxConsecutiveFailures` | number | No | Failures before auto-pause (default: `5`) |
### Example: Recurring Cron Schedule
```bash theme={null}
curl -X POST https://api.webrun.ai/cron-jobs \
-H "Authorization: Bearer wr_xxx" \
-H "Content-Type: application/json" \
-d '{
"name": "Daily price check",
"description": "Check competitor prices every morning",
"environmentId": "",
"policyId": "665a1f...abc",
"scheduleType": "cron",
"scheduleCron": "0 9 * * 1-5",
"timezone": "America/New_York",
"prompt": "Go to competitor.com/pricing and extract all plan prices",
"startingUrl": "https://competitor.com/pricing",
"outputType": "structured",
"outputSchema": {
"type": "object",
"properties": {
"plans": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"price": { "type": "number" }
}
}
}
}
},
"deliveryMode": "webhook",
"webhook": {
"name": "Price Updates",
"url": "https://api.yoursite.com/webhooks/prices",
"auth": "Bearer your-secret-token",
"submittedData": "ai_response"
}
}'
```
### Example: Fixed Interval
```bash theme={null}
curl -X POST https://api.webrun.ai/cron-jobs \
-H "Authorization: Bearer wr_xxx" \
-H "Content-Type: application/json" \
-d '{
"name": "Inventory monitor",
"environmentId": "",
"policyId": null,
"scheduleType": "every",
"scheduleInterval": "2h",
"prompt": "Check the inventory page and report any out-of-stock items",
"startingUrl": "https://store.example.com/inventory",
"deliveryMode": "webhook",
"webhook": {
"name": "Inventory Alert",
"url": "https://api.yoursite.com/webhooks/inventory",
"submittedData": "ai_response"
}
}'
```
### Example: One-Time Scheduled Run
```bash theme={null}
curl -X POST https://api.webrun.ai/cron-jobs \
-H "Authorization: Bearer wr_xxx" \
-H "Content-Type: application/json" \
-d '{
"name": "Q1 report export",
"environmentId": "",
"scheduleType": "at",
"scheduleAt": "2026-04-01T06:00:00Z",
"prompt": "Log into the dashboard and export the Q1 revenue report as PDF",
"deliveryMode": "bot"
}'
```
**Response (201 Created):**
```json theme={null}
{
"success": true,
"cronJob": {
"_id": "664a1b2c3d4e5f6a7b8c9d0e",
"name": "Daily price check",
"environmentId": "683a1f2e4b0c1d2e3f4a5b6c",
"policyId": "665a1f...abc",
"scheduleType": "cron",
"scheduleCron": "0 9 * * 1-5",
"timezone": "America/New_York",
"prompt": "Go to competitor.com/pricing and extract all plan prices",
"status": "active",
"nextRunAt": "2026-02-25T14:00:00.000Z",
"createdAt": "2026-02-24T10:00:00.000Z"
}
}
```
### Errors
| Status | Message | Cause |
| ------ | ------------------------------------------------------------- | ----------------------------------------------------- |
| 400 | name is required | Missing or empty `name` |
| 400 | prompt is required | Missing or empty `prompt` |
| 400 | Valid environmentId is required | Missing or invalid environment ID |
| 400 | Maximum of N cron jobs per user | User limit reached |
| 400 | webhook config is required when deliveryMode includes webhook | Missing webhook config |
| 404 | Environment not found | Environment does not exist or belongs to another user |
***
## Get a Trigger
Returns a single trigger with its 10 most recent runs.
```
GET /cron-jobs/:id
```
```bash theme={null}
curl https://api.webrun.ai/cron-jobs/ \
-H "Authorization: Bearer wr_xxx"
```
**Response:**
```json theme={null}
{
"success": true,
"cronJob": {
"_id": "664a1b2c3d4e5f6a7b8c9d0e",
"name": "Daily price check",
"status": "active",
"nextRunAt": "2026-02-25T14:00:00.000Z",
"consecutiveFailures": 0
},
"recentRuns": [
{
"_id": "run_abc123",
"cronJobId": "664a1b2c3d4e5f6a7b8c9d0e",
"status": "completed",
"createdAt": "2026-02-24T14:00:00.000Z"
}
]
}
```
### Errors
| Status | Message | Cause |
| ------ | ------------------ | ----------------------------------------- |
| 404 | Cron job not found | Invalid ID or job belongs to another user |
***
## Update a Trigger
Update any field on an existing trigger. Only include the fields you want to change.
```
PUT /cron-jobs/:id
Content-Type: application/json
```
```bash theme={null}
curl -X PUT https://api.webrun.ai/cron-jobs/ \
-H "Authorization: Bearer wr_xxx" \
-H "Content-Type: application/json" \
-d '{
"scheduleCron": "0 8 * * 1-5",
"timezone": "Europe/London"
}'
```
**Response:**
```json theme={null}
{
"success": true,
"cronJob": {
"_id": "664a1b2c3d4e5f6a7b8c9d0e",
"name": "Daily price check",
"scheduleCron": "0 8 * * 1-5",
"timezone": "Europe/London",
"nextRunAt": "2026-02-25T08:00:00.000Z"
}
}
```
Changing schedule-related fields (`scheduleType`, `scheduleAt`, `scheduleInterval`, `scheduleCron`, `timezone`) automatically recomputes `nextRunAt`.
### Errors
| Status | Message | Cause |
| ------ | ------------------ | ----------------------------------------- |
| 404 | Cron job not found | Invalid ID or job belongs to another user |
***
## Delete a Trigger
Permanently deletes a trigger and all its run history.
```
DELETE /cron-jobs/:id
```
```bash theme={null}
curl -X DELETE https://api.webrun.ai/cron-jobs/ \
-H "Authorization: Bearer wr_xxx"
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Cron job deleted"
}
```
### Errors
| Status | Message | Cause |
| ------ | ------------------ | ----------------------------------------- |
| 404 | Cron job not found | Invalid ID or job belongs to another user |
***
## Pause a Trigger
Pause an active trigger. The trigger will stop executing until resumed.
```
POST /cron-jobs/:id/pause
```
```bash theme={null}
curl -X POST https://api.webrun.ai/cron-jobs//pause \
-H "Authorization: Bearer wr_xxx"
```
**Response:**
```json theme={null}
{
"success": true,
"cronJob": {
"_id": "664a1b2c3d4e5f6a7b8c9d0e",
"status": "paused"
}
}
```
### Errors
| Status | Message | Cause |
| ------ | --------------------------------------- | ----------------------------------------- |
| 400 | Cannot pause a job with status "paused" | Job is not currently active |
| 404 | Cron job not found | Invalid ID or job belongs to another user |
***
## Resume a Trigger
Resume a paused trigger. Resets the consecutive failure counter and recomputes the next run time.
```
POST /cron-jobs/:id/resume
```
```bash theme={null}
curl -X POST https://api.webrun.ai/cron-jobs//resume \
-H "Authorization: Bearer wr_xxx"
```
**Response:**
```json theme={null}
{
"success": true,
"cronJob": {
"_id": "664a1b2c3d4e5f6a7b8c9d0e",
"status": "active",
"consecutiveFailures": 0,
"nextRunAt": "2026-02-25T14:00:00.000Z"
}
}
```
### Errors
| Status | Message | Cause |
| ------ | ---------------------------------------- | ----------------------------------------- |
| 400 | Cannot resume a job with status "active" | Job is not currently paused |
| 404 | Cron job not found | Invalid ID or job belongs to another user |
***
## Run a Trigger Manually
Immediately run a trigger outside of its normal schedule. The run executes in the background.
```
POST /cron-jobs/:id/trigger
```
```bash theme={null}
curl -X POST https://api.webrun.ai/cron-jobs//trigger \
-H "Authorization: Bearer wr_xxx"
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Job triggered. Check runs endpoint for results."
}
```
Manual triggers run independently of the trigger's schedule. The trigger's `nextRunAt` is not affected.
### Errors
| Status | Message | Cause |
| ------ | ------------------ | ----------------------------------------- |
| 404 | Cron job not found | Invalid ID or job belongs to another user |
***
## List Trigger Runs
Returns paginated execution history for a trigger.
```
GET /cron-jobs/:id/runs
```
| Parameter | Location | Default | Description |
| --------- | -------- | ------- | ------------------------- |
| `page` | Query | `1` | Page number |
| `limit` | Query | `20` | Results per page (max 50) |
```bash theme={null}
curl "https://api.webrun.ai/cron-jobs//runs?page=1&limit=10" \
-H "Authorization: Bearer wr_xxx"
```
**Response:**
```json theme={null}
{
"success": true,
"runs": [
{
"_id": "run_abc123",
"cronJobId": "664a1b2c3d4e5f6a7b8c9d0e",
"status": "completed",
"createdAt": "2026-02-24T14:00:00.000Z"
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 45,
"totalPages": 5
}
}
```
***
## Get a Specific Run
Returns details for a single run.
```
GET /cron-jobs/:id/runs/:runId
```
```bash theme={null}
curl https://api.webrun.ai/cron-jobs//runs/ \
-H "Authorization: Bearer wr_xxx"
```
**Response:**
```json theme={null}
{
"success": true,
"run": {
"_id": "run_abc123",
"cronJobId": "664a1b2c3d4e5f6a7b8c9d0e",
"status": "completed",
"createdAt": "2026-02-24T14:00:00.000Z"
}
}
```
### Errors
| Status | Message | Cause |
| ------ | ------------------ | ------------------------------------------------- |
| 404 | Cron job not found | Invalid job ID or job belongs to another user |
| 404 | Run not found | Invalid run ID or run does not belong to this job |
***
## Common Errors
All error responses follow this format:
```json theme={null}
{
"success": false,
"message": "Description of the error"
}
```
| Status | Message | Cause |
| ------ | -------------------------- | ---------------------------------------- |
| 401 | API key required | Missing `Authorization` header |
| 401 | Invalid or revoked API key | API key is incorrect or has been revoked |
| 403 | Account is deactivated | User account is disabled |
| 500 | Server error | Unexpected server-side failure |
***
What environments are and when to use them
Configure webhook endpoints for result delivery
Get validated JSON or CSV data from task results
Create and manage environments programmatically
# MCP Quickstart
Source: https://docs.webrun.ai/getting-started/mcp-quickstart
Add browser automation to Claude, ChatGPT, Claude Code, Cursor, VS Code and Cline via MCP
## What is MCP?
The Model Context Protocol (MCP) allows AI assistants like Claude, ChatGPT and Cline to access external tools and services. By adding the WebRun MCP server, you give these assistants the ability to browse the web autonomously.
***
## Choose your path
There is one server URL for every client:
```
https://api.webrun.ai/mcp
```
* **Claude and ChatGPT** connect with that URL and no API key at all — you authorize WebRun once, in the browser. Start at [Connect with OAuth](#connect-with-oauth-claude-and-chatgpt).
* **Everything with a config file** (Claude Code, Cursor, Claude Desktop, VS Code, Cline) uses the same URL plus an `API-Key` header. A second header, `Environment-Id`, is optional — it decides whether tasks run on a persistent machine or a throwaway one. Start at [Connect with an API key](#connect-with-an-api-key).
Your API key travels in a header, never in the URL. That keeps it out of browser history, shell history and proxy logs, and it means you can rotate the key without touching a URL you may have already copied somewhere else.
***
## Connect with OAuth (Claude and ChatGPT)
No API key needed.
In Claude or ChatGPT, go to **Settings → Connectors → Add custom connector**.
```
https://api.webrun.ai/mcp
```
Approve the connection when prompted. WebRun issues the credentials for you.
If you have more than one environment, the one you pick during authorization becomes the connection's default — the assistant will use it without being told.
***
## Connect with an API key
Every example below is complete: the same URL, your API key, and the environment you want the assistant to work in. Copy the whole block.
### Claude Code
```bash theme={null}
claude mcp add --transport http webrun https://api.webrun.ai/mcp --header "API-Key: YOUR_API_KEY" --header "Environment-Id: 65f0a1b2c3d4e5f60718293a"
```
`--header` is repeatable — that is how both values are passed in one command.
Or, to share the connection with a project, add this to `.mcp.json` at the repo root:
```json theme={null}
{
"mcpServers": {
"webrun": {
"type": "http",
"url": "https://api.webrun.ai/mcp",
"headers": {
"API-Key": "${WEBRUN_API_KEY}",
"Environment-Id": "65f0a1b2c3d4e5f60718293a"
}
}
}
}
```
Delete the `Environment-Id` line to get a fresh disposable machine for every task.
`"type": "http"` is required. Claude Code reads a `url` entry with no `type` as a local command, and the server will not start.
`${WEBRUN_API_KEY}` is expanded from your environment when the file loads, so the file is safe to commit. The environment ID is not a secret and can stay inline.
***
### Cursor
Add this to `~/.cursor/mcp.json`, or `.cursor/mcp.json` inside a project:
```json theme={null}
{
"mcpServers": {
"webrun": {
"url": "https://api.webrun.ai/mcp",
"headers": {
"API-Key": "${env:WEBRUN_API_KEY}",
"Environment-Id": "65f0a1b2c3d4e5f60718293a"
}
}
}
}
```
Delete the `Environment-Id` line to get a fresh disposable machine for every task.
Cursor does not use a `type` field for remote servers, and its variable syntax is `${env:NAME}`.
***
### Claude Desktop
Claude Desktop's configuration file only supports local (stdio) servers, so connect through **Settings → Connectors** using the [OAuth flow](#connect-with-oauth-claude-and-chatgpt) above — no key, no file editing, and you choose the environment during authorization.
If you must use the config file, bridge it with `mcp-remote`:
```json theme={null}
{
"mcpServers": {
"webrun": {
"command": "npx",
"args": [
"-y", "mcp-remote", "https://api.webrun.ai/mcp",
"--header", "API-Key:${WEBRUN_KEY}",
"--header", "Environment-Id:65f0a1b2c3d4e5f60718293a"
],
"env": { "WEBRUN_KEY": "YOUR_API_KEY" }
}
}
}
```
Delete the second `--header` pair to get a fresh disposable machine for every task.
The headers are written without a space after the colon on purpose — `mcp-remote` splits `--header` arguments on spaces.
After editing, quit Claude Desktop completely and reopen it.
***
### VS Code
Add this to `.vscode/mcp.json` — note the top-level key is `servers`, not `mcpServers`:
```json theme={null}
{
"servers": {
"webrun": {
"type": "http",
"url": "https://api.webrun.ai/mcp",
"headers": {
"API-Key": "${input:webrun-api-key}",
"Environment-Id": "65f0a1b2c3d4e5f60718293a"
}
}
},
"inputs": [
{ "type": "promptString", "id": "webrun-api-key", "description": "WebRun API key", "password": true }
]
}
```
Delete the `Environment-Id` line to get a fresh disposable machine for every task.
VS Code prompts for the key on first use and stores it securely rather than in the file.
***
### Cline
Open the Cline panel, use the menu in its top-right corner, choose **MCP Servers**, and edit `cline_mcp_settings.json`:
```json theme={null}
{
"mcpServers": {
"webrun": {
"type": "streamableHttp",
"url": "https://api.webrun.ai/mcp",
"headers": {
"API-Key": "YOUR_API_KEY",
"Environment-Id": "65f0a1b2c3d4e5f60718293a"
}
}
}
}
```
Delete the `Environment-Id` line to get a fresh disposable machine for every task.
`"type": "streamableHttp"` is camelCase with no hyphen. Writing `streamable-http`, or leaving `type` out, makes Cline fall back to SSE and the connection fails with a 405.
Cline does not expand environment variables in this file, so the key goes in literally — keep the file out of version control.
***
## Environments
An environment is a persistent remote machine with its own browser, file system, and desktop, so logins, cookies, and downloaded files survive between tasks.
**The `Environment-Id` header is optional.** Both ways of running are fully supported:
| Environment ID | What you get |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| **Provided** | Every task runs on that persistent environment. Logins, cookies, downloaded files and browser profile carry over from one task to the next |
| **Omitted** | Every task gets its own temporary browser, created when the task starts and discarded when it ends. Nothing carries over |
Leaving the header out is a normal configuration, not a broken one. Omit it when every task should start from a clean slate, and add an environment when you need the browser to remember something — a logged-in account, a downloaded file, an installed extension.
**Where to find the ID:** ask the assistant to list your environments, or copy it from the Environment page in the dashboard. It is a 24-character hex string, and it is not a secret — it is safe to commit.
**Three ways to choose one:**
| How | When |
| --------------------------------------------- | --------------------------------------------------------- |
| The `Environment-Id` header | A config file — sets the default for the whole connection |
| Chosen during OAuth authorization | Claude and ChatGPT connectors, which have no config file |
| The `environmentId` argument on any task tool | Per task, overriding whatever the connection uses |
The per-task argument means you can keep one connection and still send one task to your logged-in shopping profile and the next to a clean machine.
***
## Your First Browser Task
Once configured, you can ask Claude to browse the web:
**Example Prompts:**
* "Search Google for Anthropic and summarize the first result"
* "Go to example.com and extract all the product prices"
* "Navigate to LinkedIn, search for software engineers in SF, and list the top 5 results"
**What happens:**
1. Claude recognizes your request requires web browsing
2. It calls the WebRun MCP tool with your task
3. An AI agent executes the task in a real browser
4. Results are returned to Claude
5. Claude presents the information to you
For multi-step work, ask for a session instead of a one-off task — "Create a browser session, go to Amazon, search for wireless keyboards, and tell me the top 3 results." The assistant calls `create_session` once and then `send_task` for each follow-up, so the browser keeps its place between steps.
***
## Available Tools
The WebRun MCP server exposes 21 tools.
**Browser tasks**
| Tool | What it does |
| ------------------- | ------------------------------------------------------------------------ |
| `browser_task` | Run a one-off task in a real browser; creates a session, runs, cleans up |
| `create_session` | Start a persistent session for multi-step work |
| `send_task` | Send another task to an existing session |
| `get_task_status` | Check a running task; reports when input is needed |
| `screenshot` | Capture the current page of a live session |
| `list_sessions` | List active sessions |
| `terminate_session` | End a session and free its resources |
**Controlling a running task**
| Tool | What it does |
| --------------------- | ----------------------------------------------------------------- |
| `pause_session_task` | Pause the task currently running |
| `resume_session_task` | Resume a paused task |
| `stop_session_task` | Cancel the task, keep the session alive |
| `guardrail_response` | Answer when the agent hits a CAPTCHA, 2FA prompt, or confirmation |
**Environments**
| Tool | What it does |
| ------------------- | -------------------------------------------------------------------- |
| `list_environments` | List persistent environments and show which one this connection uses |
**Workflows** — saved, reusable automations
| Tool | What it does |
| ------------------------------------- | -------------------------------------- |
| `list_workflows` · `get_workflow` | Browse saved workflows and inspect one |
| `create_workflow` · `update_workflow` | Author and edit them |
| `trigger_workflow` | Run one now |
**Scheduled agents** — automations that run on a timer
| Tool | What it does |
| ---------------------------------------------- | ------------------------------------ |
| `create_agent` | Schedule a recurring or one-time run |
| `list_agents` · `pause_agent` · `resume_agent` | Manage them |
[Full MCP Reference →](/integrations/mcp-server)
***
## Troubleshooting
### Tools not appearing (Claude Code)
Run `claude mcp get webrun`. The most common cause is a missing `"type": "http"` — without it the entry is treated as a local command.
### Tools not appearing (Cursor / VS Code)
Confirm the top-level key: Cursor uses `mcpServers`, VS Code uses `servers`.
### It connects but every task fails
The server lists its tools without a key, so a connection with a missing or wrong key looks healthy until the first task. Check the `API-Key` header value.
### Authentication errors
Keys start with `wr_` or `enig_`. Confirm the key is active in the dashboard and that the account has balance.
### "Environment not found"
The ID must be a 24-character hex string belonging to your account. Ask the assistant to list your environments.
### Session timeouts
Sessions expire after **5 minutes idle**. A single task runs up to **20 minutes** by default — pass `maxDuration` for longer, or split the work.
Claude Code, Cursor and VS Code pick up config changes without a restart. Only Claude Desktop needs a full quit and reopen.
***
## Next Steps
All tools, parameters, and advanced patterns
Chain multiple browser tasks
Respond to human-in-the-loop requests
Watch browser sessions live
# Overview
Source: https://docs.webrun.ai/getting-started/overview
Real-time browser automation infrastructure for AI agents
WebRun is real-time browser automation infrastructure for AI agents. Give it a task in plain English, and an AI agent executes it in a real browser, clicking, typing, navigating, and extracting data autonomously.
**Key capabilities:**
* **Sub-100ms decisions**: Hybrid CNN-LLM architecture delivers production-ready speed
* **Real-time video streaming**: Watch sessions live as they execute
* **Human-in-the-loop controls**: Manual takeover for credentials, approvals, or edge cases
* **Multiple integration paths**: REST, WebSocket, MCP, or OpenAI-compatible APIs
***
## What WebRun Handles
### Data Extraction at Scale
Extract structured data from dynamic websites without building custom scrapers.
**Example task:** "Search LinkedIn for engineering managers in San Francisco with 5+ years experience. Return their profiles as JSON with name, title, company, and LinkedIn URL."
### Form Automation
Navigate multi-step forms with conditional logic and dynamic fields.
**Example task:** "Fill out this insurance quote form using the customer data in the attached JSON. Handle the multi-step workflow and return the final quote amount."
### E-commerce Workflows
Search products, compare prices, add items to cart, all through natural language commands.
**Example task:** "Find wireless keyboards under \$50 on Amazon, filter by 4+ star ratings, and return the top 3 with price and review count."
### Cross-Site File Transfers
Download files from one platform and upload them to another, moving documents, reports, and data between systems autonomously.
**Example task:** "Download the monthly sales report from our analytics dashboard and upload it to the shared Google Drive folder."
### Adaptive Testing
Test web applications without maintaining brittle test selectors. The agent adapts to UI changes automatically.
**Example task:** "Go through the signup flow with invalid email formats and document all validation errors you encounter."
***
## Sessions and Tasks
A **session** is an isolated browser instance. A **task** is a single instruction you give that session. Sessions can run indefinitely while active and expire after 5 minutes of inactivity, letting you chain multiple tasks sequentially.
```
Session (sess_abc123)
├── Task 1: Navigate to site → completed
├── Task 2: Search for product → completed
└── Task 3: Extract data → completed
```
Sessions terminate when you explicitly end them or when they hit the timeout. Always terminate sessions when finished to avoid unnecessary charges.
[Sessions documentation](/concepts/sessions) | [Tasks documentation](/concepts/tasks)
***
## Response Model
Most tasks complete in 10-40 seconds. WebRun waits up to 50 seconds before returning. If your task finishes within that window, you get the result inline. If it takes longer, you poll for the result.
This gives you the simplicity of synchronous APIs for typical use cases, with async polling available for complex workflows.
[Response model details](/concepts/response-model)
***
## Guardrails
When the agent needs human input (credentials, clarification, purchase approval), it triggers a guardrail and pauses. Your application detects this via the API response and provides the needed information to continue.
**Common triggers:** Login forms, payment confirmations, CAPTCHAs, ambiguous instructions
For login credentials, you can bypass guardrails entirely by providing [secrets](/usage-guides/secrets) upfront when creating the session. Secrets are matched to websites by domain pattern and are never stored; they exist only in the session's memory and are discarded when the session ends.
Alternatively, use [environments](/environments/overview) to persist login cookies and files across sessions: log in once and reuse the saved browser state for future tasks.
[Guardrails documentation](/concepts/guardrails) | [Secrets documentation](/usage-guides/secrets) | [Environments documentation](/environments/overview)
***
## Integration Options
Choose the integration method that fits your stack:
| Method | Best For | Real-time Updates |
| --------------------- | ------------------------------------------------ | ----------------- |
| **REST API** | Serverless functions, simple integrations | Poll for updates |
| **WebSocket** | Live dashboards, real-time monitoring | Yes |
| **OpenAI-Compatible** | Drop-in replacement for LangChain, Vercel AI SDK | Stream or poll |
| **MCP Server** | Claude Desktop, Cline, MCP clients | Session-based |
**Quick decision tree:**
* **Single task, auto-terminate?** → `POST /start/run-task`
* **Multiple tasks in sequence?** → `POST /start/start-session` + `/send-message`
* **Using LangChain or OpenAI SDK?** → `POST /v1/chat/completions`
* **Claude Desktop or MCP client?** → MCP Server
[REST API](/integrations/rest-api) | [WebSocket](/integrations/websocket) | [OpenAI-Compatible](/integrations/openai-compatible) | [MCP Server](/integrations/mcp-server)
***
## Why WebRun vs Traditional Automation
Traditional browser automation (Selenium, Playwright, Puppeteer) requires writing code that targets specific page elements. When the website changes (new class names, restructured HTML, different IDs), your automation breaks.
WebRun's AI agents don't rely on selectors. They see the page visually, understand the content semantically, and adapt to changes automatically. No maintenance when websites update their UI.
**Speed comparison:** WebRun delivers sub-100ms response times per action. Traditional tools average \~50ms per action, but require manual coding and ongoing maintenance that compounds costs at scale.
***
## Get Started
First automation task in 5 minutes
Complete endpoint documentation
REST, WebSocket, OpenAI, MCP
Watch sessions execute in real-time
# Quickstart
Source: https://docs.webrun.ai/getting-started/quickstart
Run your first browser automation task in under 5 minutes
## Get Your API Key
1. Sign up at [webrun.ai](https://webrun.ai)
2. Navigate to **Settings → API Keys**
3. Click **Create API Key** and save it
```
wr_xxxxxxxxxxxxxxxxxxxxxxxxxxxx
```
Sessions cost money until terminated. Set `terminateOnCompletion: true` on your final task or explicitly terminate when done.
***
## Run Your First Task
The simplest approach: one API call that creates a session, runs your task, and auto-terminates.
```bash theme={null}
curl -X POST https://api.webrun.ai/start/run-task \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"task": {
"prompt": "Go to google.com and search for Anthropic"
}
}'
```
**If the task completes within 50 seconds**, you get the result immediately:
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3",
"taskId": "x9y8z7",
"type": "task_completed",
"data": {
"message": "Successfully searched for Anthropic on Google"
},
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"completion_time": 23.5,
"cost": 0.0124
}
}
```
**If the task takes longer**, you'll get a polling URL:
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3",
"taskId": "x9y8z7",
"status": "pending",
"pollUrl": "https://api.webrun.ai/task/a1b2c3/x9y8z7"
}
```
Poll the URL every 2-3 seconds until the task completes. Most tasks finish in 10-40 seconds, so faster polling wastes API quota while slower polling adds latency.
***
## Multi-Task Sessions
For multiple tasks in sequence, create a persistent session:
**1. Create the session**
```bash theme={null}
curl -X POST https://api.webrun.ai/start/start-session \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"mode": "default",
"task": {
"prompt": "Go to amazon.com",
"startingUrl": "https://amazon.com"
}
}'
```
**2. Send follow-up tasks**
```bash theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "SESSION_ID",
"message": {
"actionType": "newTask",
"newState": "start",
"prompt": "Search for wireless keyboards",
"startingUrl": "https://amazon.com"
}
}'
```
**3. Terminate when finished**
```bash theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "SESSION_ID",
"message": {
"actionType": "state",
"newState": "terminate"
}
}'
```
Alternatively, set `terminateOnCompletion: true` on your last task to auto-terminate the session.
[Multi-task workflows guide](/usage-guides/multi-task-workflows)
***
## Polling for Results
When a task returns `status: "pending"`, poll the URL until completion.
```javascript theme={null}
async function runTask(prompt, apiKey) {
// Start the task
const response = await fetch("https://api.webrun.ai/start/run-task", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({ task: { prompt } })
});
const data = await response.json();
// Return immediately if complete
if (data.type === "task_completed") {
return data;
}
// Poll if still running
if (data.status === "pending") {
return await pollForResult(data.sessionId, data.taskId, apiKey);
}
throw new Error(data.message || "Task failed");
}
async function pollForResult(sessionId, taskId, apiKey) {
const maxAttempts = 60; // 2 minutes
const interval = 2000; // Poll every 2 seconds
for (let i = 0; i < maxAttempts; i++) {
const res = await fetch(
`https://api.webrun.ai/task/${sessionId}/${taskId}`,
{ headers: { "Authorization": `Bearer ${apiKey}` } }
);
const data = await res.json();
if (data.type === "task_completed") return data;
if (data.type === "guardrail_trigger") return data;
if (!data.success && data.type === "failed") {
throw new Error(data.error);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error("Task timeout after 2 minutes");
}
// Usage
const result = await runTask("Search Google for Anthropic", "wr_xxx");
console.log(result.data.message);
console.log(`Cost: $${result.usage.cost}`);
```
This handles both instant and long-running tasks automatically.
***
## Real-Time Updates with WebSocket
For live agent thoughts and action notifications, use WebSocket. This requires more setup but gives you sub-second visibility into task execution.
[WebSocket integration guide](/integrations/websocket)
***
## Next Steps
Chain multiple tasks in a session
Set up Claude Desktop integration
Watch sessions execute in real-time
Reduce costs and improve efficiency
Upload files for the agent to use in sessions
# Workflows: n8n, Make
Source: https://docs.webrun.ai/getting-started/workflow-quickstart
Integrate WebRun with no-code automation platforms
## Understanding WebRun's Response Model
Before setting up your workflow, understand how WebRun returns results:
**Fast Tasks (\< 50 seconds):**
* Single HTTP request returns the result directly
* No polling needed
* Most simple tasks (search, navigate, extract) complete in 10-40 seconds
**Longer Tasks (> 50 seconds):**
* Initial request returns a `pollUrl`
* You must poll this URL until task completes
* Required for complex multi-step automations
***
## Platform Compatibility
| Platform | HTTP Timeout | WebRun Compatibility | Recommended Approach |
| ------------ | -------------------------- | -------------------- | -------------------------------- |
| **n8n** | 100s (Cloud) | Excellent | Direct call works for most tasks |
| **Make.com** | 30s default, up to 300s | Good | Set timeout to 60s+ |
| **Zapier** | 30s (fixed, cannot change) | Requires polling | Always use polling pattern |
***
## n8n Integration
### Why n8n Works Well
n8n Cloud has a 100-second timeout, comfortably above WebRun's 50-second inline window. Most tasks will return results directly without polling.
### Method 1: Simple Task (Direct Response)
Use when you're confident the task takes \< 50 seconds.
**Step 1: Add HTTP Request Node**
* Method: POST
* URL: `https://api.webrun.ai/start/run-task`
* Authentication: Header Auth
* Name: `Authorization`
* Value: `Bearer YOUR_API_KEY`
**Step 2: Configure Body**
* Body Content Type: JSON
* Body:
```json theme={null}
{
"prompt": "Go to google.com and search for 'Anthropic AI'"
}
```
**Step 3: Use the Response**
* Access `{{ $json.result.data.message }}` for the task output
* Access `{{ $json.result.usage.cost }}` for cost tracking
### Method 2: With Polling (For Longer Tasks)
Use when task might exceed 50 seconds.
**Workflow Structure:**
```
[HTTP Request: Start Task]
→ [IF: Check if pending]
→ Yes → [Loop: Poll until complete]
→ No → [Continue with result]
```
**Step-by-Step:**
1. **HTTP Request Node**: Start Task
* URL: `https://api.webrun.ai/start/run-task`
* Method: POST
* Authentication: Header Auth (`Authorization: Bearer YOUR_API_KEY`)
* Body:
```json theme={null}
{
"prompt": "Your complex task here"
}
```
2. **IF Node**: Check Status
* Condition: `{{ $json.status }}` equals `pending`
* Route 1 (True): Go to polling loop
* Route 2 (False): Task complete, continue
3. **Wait Node** (on True route)
* Duration: 3 seconds
4. **HTTP Request Node**: Poll
* URL: `{{ $('HTTP Request').item.json.pollUrl }}`
* Method: GET
* Authentication: Header Auth (`Authorization: Bearer YOUR_API_KEY`)
5. **Loop Back to IF Node**
* Use the loop node or manually route back to the IF node
* Continue until `status !== "pending"`
***
## Make.com Integration
### Important: Increase HTTP Timeout
Make.com's default timeout is 30 seconds, too short for WebRun. **You must increase it to 60+ seconds.**
### Method 1: Simple Task (Extended Timeout)
**Step 1: Add HTTP → Make a Request Module**
**Step 2: Configure Request**
* URL: `https://api.webrun.ai/start/run-task`
* Method: POST
* Headers:
* `Authorization`: `Bearer YOUR_API_KEY`
* `Content-Type`: `application/json`
* Body type: Raw
* Content type: JSON
* Request content:
```json theme={null}
{
"prompt": "Search Google for Anthropic and return first result"
}
```
**Step 3: Set Timeout (CRITICAL)**
* Click "Show advanced settings"
* Set **Timeout**: `60` (seconds), or higher for complex tasks
* Maximum allowed: 300 seconds
**Step 4: Parse Response**
* If `status` = `complete`: Use `result.data.message`
* If `status` = `pending`: Implement polling (Method 2)
### Method 2: With Polling (Recommended for Production)
**Scenario Structure:**
```
[HTTP: Start Task]
→ [Router]
→ Route 1 (status = complete): [Continue]
→ Route 2 (status = pending): [Sleep 3s] → [HTTP: Poll] → [Loop]
```
**Step-by-Step:**
1. **HTTP Module**: Start Task
* URL: `https://api.webrun.ai/start/run-task`
* Method: POST
* Headers: `Authorization`, `Content-Type`
* Timeout: 60+ seconds
* Body:
```json theme={null}
{
"prompt": "Your task here"
}
```
2. **Router Module**
* Route 1 Filter: `status` equals `complete`
* Route 2 Filter: `status` equals `pending`
3. **On Route 2**: Add Sleep Module
* Duration: 3000ms
4. **HTTP Module**: Poll for Result
* URL: `{{pollUrl}}`
* Method: GET
* Headers: `Authorization: Bearer YOUR_API_KEY`
5. **Loop Back or Use Repeater**
* Continue polling until `type` = `task_completed`
***
## Zapier Integration
### Important Limitation
Zapier has a **fixed 30-second HTTP timeout** that cannot be changed. Since WebRun's inline response window is 50 seconds, **you must always use the polling pattern** with Zapier.
### Why Polling is Required
Even if your task might complete in 20 seconds, Zapier may timeout before WebRun responds. The polling pattern avoids this timeout issue regardless of task duration.
### Step-by-Step Setup
**Step 1: Trigger**
Choose your trigger (e.g., "New Row in Google Sheets", "New Form Response", etc.)
**Step 2: Start the WebRun Task**
* App: Webhooks by Zapier
* Event: POST
* URL: `https://api.webrun.ai/start/run-task`
* Payload Type: JSON
* Data:
```json theme={null}
{
"prompt": "Your task description here"
}
```
* Headers:
* `Authorization`: `Bearer YOUR_API_KEY`
* `Content-Type`: `application/json`
**Step 3: Add Delay**
* App: Delay by Zapier
* Event: Delay For
* Duration: 30 seconds (or estimated task time)
**Step 4: Poll for Result**
* App: Webhooks by Zapier
* Event: GET
* URL: Construct from Step 2:
* `https://api.webrun.ai/task/{{steps.2.sessionId}}/{{steps.2.taskId}}`
* Or use `{{steps.2.pollUrl}}` if available
* Headers:
* `Authorization`: `Bearer YOUR_API_KEY`
**Step 5: Check if Complete**
* App: Filter by Zapier
* Condition: `type` equals `task_completed`
* If not complete, use Paths to retry polling
**Step 6: Use the Result**
* Access the task output: `{{steps.4.data.message}}`
* Access cost: `{{steps.4.usage.cost}}`
### Alternative: Use Looping (Zapier Beta)
If you have access to Zapier's Looping feature:
1. Start task
2. Loop: Poll every 5 seconds until `type` = `task_completed`
3. Continue with result
***
## Platform Comparison Summary
| Feature | n8n | Make.com | Zapier |
| ------------------------ | ------------- | ------------------------- | ----------------- |
| Direct response possible | Yes | Yes (with timeout config) | No |
| Polling complexity | Low | Medium | High |
| Max HTTP timeout | 100s | 300s | 30s (fixed) |
| Recommended for | All use cases | All use cases | Simple tasks only |
| Loop/retry support | Native | Native | Limited |
***
## Common Patterns
### Pattern 1: Form → Browser Task → Store Result
**Trigger:** Form submission
**Action:** Run WebRun task with form data
**Output:** Store result in database/sheet
**Example Use Case:** Lead enrichment: form captures company name, WebRun researches company details, result stored in CRM.
### Pattern 2: Scheduled Research
**Trigger:** Schedule (daily/weekly)
**Action:** Run research task
**Output:** Send email summary
**Example Use Case:** Daily competitor monitoring: scrape competitor websites, compile changes, email report.
### Pattern 3: Lead Enrichment
**Trigger:** New lead in CRM
**Action:** Research company/person via browser
**Output:** Update CRM record
**Example Use Case:** Sales automation: new lead added to Salesforce, WebRun finds LinkedIn profile and company info, updates Salesforce.
***
## Troubleshooting
### "Connection timed out" Error
**n8n:** Should not happen if task \< 100s. Check network and API key.
**Make.com:** Increase timeout in advanced settings to 60+ seconds.
**Zapier:** Expected. Implement polling pattern.
### Task Returns "pending" Status
Normal for tasks > 50 seconds. Implement polling to get final result.
### Empty or Missing Result
Check that you're accessing the correct response path:
* **Direct response:** `result.data.message`
* **Polled response:** `data.message`
### High Costs
* Set `terminateOnCompletion: true` in your task payload
* Monitor costs in the WebRun dashboard
* See [Cost Optimization](/usage-guides/cost-optimization) for tips
***
## Next Steps
Full REST API documentation
Tips to reduce costs
Respond to human-in-the-loop requests
Common workflow issues
# MCP Server Reference
Source: https://docs.webrun.ai/integrations/mcp-server
Complete reference for WebRun's Model Context Protocol server
## Overview
The WebRun MCP (Model Context Protocol) server gives AI assistants browser automation through their native tool interfaces. It exposes 21 tools covering one-off tasks, persistent sessions, live task control, saved workflows, and scheduled agents, with session lifecycle handling and streaming for long-running tasks.
This is the **full reference** for the MCP server. For a quickstart guide, see [MCP Quickstart](/getting-started/mcp-quickstart).
***
## Configuration
Every client uses the same server URL:
```
https://api.webrun.ai/mcp
```
Authentication travels in headers, never in the URL.
| Header | Required | Value |
| ---------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `API-Key` | Yes, unless connecting by OAuth | Your WebRun API key |
| `Environment-Id` | No | The 24-character hex ID of a persistent environment. Provide it and tasks run on that machine, keeping state between them. Omit it and every task gets its own temporary browser, discarded when the task ends |
A key in a header stays out of browser history, shell history and proxy logs, and can be rotated without editing a URL that may already have been copied elsewhere.
### Connect with OAuth (Claude and ChatGPT)
No API key needed. In Claude or ChatGPT, open **Settings → Connectors → Add custom connector**, paste `https://api.webrun.ai/mcp`, and authorize from WebRun when prompted.
If you have more than one environment, the one you pick during authorization becomes the connection's default.
***
### Claude Code
```bash theme={null}
claude mcp add --transport http webrun https://api.webrun.ai/mcp --header "API-Key: YOUR_API_KEY" --header "Environment-Id: 65f0a1b2c3d4e5f60718293a"
```
`--header` is repeatable — that is how both values are passed in one command.
Or, to share the connection with a project, add this to `.mcp.json` at the repo root:
```json theme={null}
{
"mcpServers": {
"webrun": {
"type": "http",
"url": "https://api.webrun.ai/mcp",
"headers": {
"API-Key": "${WEBRUN_API_KEY}",
"Environment-Id": "65f0a1b2c3d4e5f60718293a"
}
}
}
}
```
Delete the `Environment-Id` line to get a fresh disposable machine for every task.
`"type": "http"` is required. Claude Code reads a `url` entry with no `type` as a local command, and the server will not start.
`${WEBRUN_API_KEY}` is expanded from your environment when the file loads, so the file is safe to commit. The environment ID is not a secret and can stay inline.
***
### Cursor
`~/.cursor/mcp.json`, or `.cursor/mcp.json` inside a project:
```json theme={null}
{
"mcpServers": {
"webrun": {
"url": "https://api.webrun.ai/mcp",
"headers": {
"API-Key": "${env:WEBRUN_API_KEY}",
"Environment-Id": "65f0a1b2c3d4e5f60718293a"
}
}
}
}
```
Delete the `Environment-Id` line to get a fresh disposable machine for every task.
Cursor does not use a `type` field for remote servers, and its variable syntax is `${env:NAME}`.
***
### Claude Desktop
Claude Desktop's configuration file only supports local (stdio) servers, so connect through **Settings → Connectors** using the OAuth flow above — no key, no file editing, and you choose the environment during authorization.
If you must use the config file, bridge it with `mcp-remote`:
```json theme={null}
{
"mcpServers": {
"webrun": {
"command": "npx",
"args": [
"-y", "mcp-remote", "https://api.webrun.ai/mcp",
"--header", "API-Key:${WEBRUN_KEY}",
"--header", "Environment-Id:65f0a1b2c3d4e5f60718293a"
],
"env": { "WEBRUN_KEY": "YOUR_API_KEY" }
}
}
}
```
Delete the second `--header` pair to get a fresh disposable machine for every task.
The headers are written without a space after the colon on purpose — `mcp-remote` splits `--header` arguments on spaces.
After editing, quit Claude Desktop completely and reopen it.
***
### VS Code
`.vscode/mcp.json` — note the top-level key is `servers`, not `mcpServers`:
```json theme={null}
{
"servers": {
"webrun": {
"type": "http",
"url": "https://api.webrun.ai/mcp",
"headers": {
"API-Key": "${input:webrun-api-key}",
"Environment-Id": "65f0a1b2c3d4e5f60718293a"
}
}
},
"inputs": [
{ "type": "promptString", "id": "webrun-api-key", "description": "WebRun API key", "password": true }
]
}
```
Delete the `Environment-Id` line to get a fresh disposable machine for every task.
VS Code prompts for the key on first use and stores it securely rather than in the file.
***
### Cline
Open the Cline panel, use the menu in its top-right corner, choose **MCP Servers**, and edit `cline_mcp_settings.json`:
```json theme={null}
{
"mcpServers": {
"webrun": {
"type": "streamableHttp",
"url": "https://api.webrun.ai/mcp",
"headers": {
"API-Key": "YOUR_API_KEY",
"Environment-Id": "65f0a1b2c3d4e5f60718293a"
}
}
}
}
```
Delete the `Environment-Id` line to get a fresh disposable machine for every task.
`"type": "streamableHttp"` is camelCase with no hyphen. Writing `streamable-http`, or leaving `type` out, makes Cline fall back to SSE and the connection fails with a 405.
Cline does not expand environment variables in this file, so the key goes in literally — keep the file out of version control.
***
## Environments
An environment is a complete persistent remote machine. It maintains its own Chrome browser, file manager, and desktop state across sessions, so browser profiles, downloaded files, cookies, and any other local state are preserved between tasks and you can pick up exactly where you left off.
**The `Environment-Id` header is optional.** Both ways of running are fully supported:
| Environment ID | What you get |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| **Provided** | Every task runs on that persistent environment. Logins, cookies, downloaded files and browser profile carry over from one task to the next |
| **Omitted** | Every task gets its own temporary browser, created when the task starts and discarded when it ends. Nothing carries over |
Leaving the header out is a normal configuration, not a broken one. Omit it when every task should start from a clean slate, and add an environment when you need the browser to remember something — a logged-in account, a downloaded file, an installed extension.
**Where to find the ID:** ask the assistant to list your environments, or copy it from the Environment page in the dashboard. It is a 24-character hex string, and it is not a secret — it is safe to commit.
**Three ways to choose one:**
| How | When |
| --------------------------------------------- | --------------------------------------------------------- |
| The `Environment-Id` header | A config file — sets the default for the whole connection |
| Chosen during OAuth authorization | Claude and ChatGPT connectors, which have no config file |
| The `environmentId` argument on any task tool | Per task, overriding whatever the connection uses |
The per-task argument means you can keep one connection and still send one task to your logged-in shopping profile and the next to a clean machine.
***
## Full Tool Reference
### browser\_task
Execute a single browser automation task. Creates a session, runs the task, and auto-terminates.
**When to use:**
* One-off research tasks
* Quick data extraction
* Simple automations that don't require follow-up
Do not use `browser_task` to run or test a saved workflow — use [`trigger_workflow`](#trigger_workflow). Only a workflow run carries the workflow's own rules, tracking and memory.
**Parameters:**
| Parameter | Type | Required | Default | Description |
| ---------------- | --------- | ----------- | ------------------ | --------------------------------------------------------------------------------------------------- |
| `prompt` | string | Yes | - | Natural language description of the task |
| `startingUrl` | string | No | null | URL to start from (e.g., "[https://google.com](https://google.com)") |
| `environmentId` | string | No | connection default | Environment to run in. Without one, the task gets its own temporary browser, discarded when it ends |
| `maxDuration` | number | No | 20 | Max task duration **in minutes** (max 60) |
| `outputType` | string | No | `"text"` | `"text"`, `"structured_json"`, or `"structured_csv"` |
| `outputSchema` | object | Conditional | - | JSON Schema for the output. Required when `outputType` is `"structured_json"` |
| `files` | string\[] | No | - | File IDs to attach (from `/files/upload`). Max 5 |
| `secrets` | object\[] | No | - | Domain-matched secrets `[{match, fields}]`, passed to the instance and not stored |
| `proxy` | object | No | none | Proxy configuration — see [Proxies](/usage-guides/proxies) |
| `policyId` | string | No | - | Policy to apply automation guardrails (domain restrictions, capability controls) |
| `model` | string | No | account default | Model name or profile key |
| `timezone` | string | No | `"UTC"` | IANA timezone name. Date-sensitive instructions ("tomorrow morning") are interpreted in it |
| `webhook` | object | No | - | Completion notification — see [Webhooks](/usage-guides/webhooks) |
| `reach_out_mode` | string | No | `"off"` | Proactive chat messages. `"off"`, `"guardrail_only"`, or `"full"` |
**Example Usage:**
```
User: "Use WebRun to search Google for 'Anthropic Claude' and summarize the first result."
Claude uses browser_task:
{
"prompt": "Go to google.com, search for 'Anthropic Claude', and summarize the first result",
"startingUrl": "https://google.com",
"maxDuration": 10
}
```
**Response:**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"result": "Anthropic is an AI safety company that created Claude, a next-generation AI assistant...",
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"cost": 0.0124
}
}
```
***
### create\_session
Create a persistent browser session for multi-step workflows. Returns a `sessionId` for subsequent commands.
**When to use:**
* Multi-step automations (search → click → extract)
* Tasks requiring context from previous steps
* When you need to send multiple commands to the same browser
**Parameters:**
| Parameter | Type | Required | Default | Description |
| ---------------- | ------ | -------- | ------------------ | --------------------------------------------------------------------------------------------------- |
| `task` | object | No | - | Initial task. Omit it to create an idle session |
| `environmentId` | string | No | connection default | Environment to run in. Without one, the task gets its own temporary browser, discarded when it ends |
| `mode` | string | No | `"default"` | Session mode |
| `model` | string | No | account default | Model name or profile key |
| `policyId` | string | No | - | Policy to apply automation guardrails |
| `proxy` | object | No | none | Proxy configuration — see [Proxies](/usage-guides/proxies) |
| `timezone` | string | No | `"UTC"` | IANA timezone name for the session |
| `reach_out_mode` | string | No | `"off"` | `"off"`, `"guardrail_only"`, or `"full"` |
The nested `task` object accepts `prompt`, `startingUrl`, `maxDuration` (minutes), `outputType`, `outputSchema`, `files`, `secrets`, `terminateOnCompletion`, and `webhook`.
**Example Usage:**
```
User: "Create a browser session and go to amazon.com"
Claude uses create_session:
{
"task": {
"prompt": "Go to amazon.com",
"startingUrl": "https://amazon.com",
"maxDuration": 20
}
}
```
**Response:**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"message": "Session created successfully. You can now send tasks to this session.",
"expiresIn": 300000,
"streamingUrl": "https://a1b2c3d4e5f6.webrun.ai"
}
```
Save the `sessionId` to send follow-up tasks with [`send_task`](#send_task).
***
### send\_task
Send a new task to an existing session.
**When to use:**
* Follow-up actions in a multi-step workflow
* Continuing work in an existing browser session
* Chaining related tasks together
**Parameters:**
| Parameter | Type | Required | Default | Description |
| ----------------------- | --------- | ----------- | ------------- | ---------------------------------------------------- |
| `sessionId` | string | Yes | - | ID from `create_session` |
| `prompt` | string | Yes | - | Task description |
| `startingUrl` | string | No | - | URL to navigate to before starting this task |
| `maxDuration` | number | No | session value | Max duration for this task **in minutes** (3–60) |
| `maxInputTokens` | number | No | session value | Max input tokens (100–3,000,000) |
| `maxOutputTokens` | number | No | session value | Max output tokens (100–1,000,000) |
| `outputType` | string | No | `"text"` | `"text"`, `"structured_json"`, or `"structured_csv"` |
| `outputSchema` | object | Conditional | - | Required when `outputType` is `"structured_json"` |
| `files` | string\[] | No | - | File IDs to attach. Max 5 |
| `secrets` | object\[] | No | - | Domain-matched secrets, not stored |
| `terminateOnCompletion` | boolean | No | false | Auto-close session after this task |
| `webhook` | object | No | - | Completion notification |
**Example Usage:**
```
User: "Now search for wireless keyboards"
Claude uses send_task:
{
"sessionId": "a1b2c3d4e5f6",
"prompt": "Search for wireless keyboards and list the top 3 results with prices",
"terminateOnCompletion": false
}
```
**Response:**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"result": "Found 3 wireless keyboards:\n1. Logitech K380 - $29.99\n2. Keychron K2 - $79.00\n3. ...",
"usage": {
"cost": 0.0089
}
}
```
Set `terminateOnCompletion: true` on your final task to avoid idle session charges.
***
### get\_task\_status
Check the status of a running task. Read-only — it reports on the task without affecting it.
**When to use:**
* Monitoring long-running tasks
* Detecting when a guardrail needs an answer
* Checking if a task completed while doing other work
**Parameters:**
| Parameter | Type | Required | Description |
| ----------- | ------ | -------- | -------------------------- |
| `sessionId` | string | Yes | Session ID |
| `taskId` | string | Yes | Task ID from previous task |
**Response (still running):**
```json theme={null}
{
"success": true,
"status": "active",
"pending": true,
"usage": {
"inputTokens": 8000,
"outputTokens": 2100,
"computeTime": 3,
"cost": 0.0067
}
}
```
**Response (completed):**
```json theme={null}
{
"success": true,
"status": "completed",
"type": "task_completed",
"data": {
"message": "Task completed successfully",
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"completion_time": 23.5
},
"usage": {
"cost": 0.0124
}
}
```
When the status reports that input is awaited, answer with [`guardrail_response`](#guardrail_response).
***
### screenshot
Capture the current browser page of an active session and return it as an inline image. Read-only.
**When to use:**
* Seeing what the agent sees before deciding the next step
* Confirming a page loaded as expected
* Debugging a task that is behaving unexpectedly
**Parameters:**
| Parameter | Type | Required | Description |
| ----------- | ------ | -------- | ----------- |
| `sessionId` | string | Yes | Session ID |
***
### list\_sessions
List all active browser sessions for the account. Read-only. Takes no parameters.
***
### terminate\_session
End a session and free its resources.
**Parameters:**
| Parameter | Type | Required | Description |
| ----------- | ------ | -------- | ----------- |
| `sessionId` | string | Yes | Session ID |
The session and any task running in it cannot be resumed afterwards.
***
### pause\_session\_task
Pause the task currently running in a session. Resume it later with `resume_session_task`.
**Parameters:** `sessionId` (string, required).
***
### resume\_session\_task
Resume a previously paused task.
**Parameters:** `sessionId` (string, required).
***
### stop\_session\_task
Cancel the task currently running, keeping the session alive for new tasks.
**Parameters:** `sessionId` (string, required).
***
### guardrail\_response
Respond when the browser agent needs human input — credentials, a CAPTCHA or 2FA prompt, a clarification, or an approval. The response is handed to the live agent, which continues acting on it.
**Parameters:**
| Parameter | Type | Required | Default | Description |
| ----------- | --------- | ----------- | ---------- | ---------------------------------------------------------------------------------- |
| `sessionId` | string | Yes | - | Session ID |
| `response` | string | Conditional | - | Your response or instructions to the agent. Required when `newState` is `"resume"` |
| `newState` | string | No | `"resume"` | `"resume"` provides the input and continues; `"deny"` declines the request |
| `files` | string\[] | No | - | File IDs to attach. Max 5 |
**Example Usage:**
```
Claude uses get_task_status and sees the agent is waiting on a login code.
Claude uses guardrail_response:
{
"sessionId": "a1b2c3d4e5f6",
"response": "The verification code is 481920",
"newState": "resume"
}
```
MCP has no manual-takeover tool. For hands-on control of the browser — clicking and typing yourself — use the REST or WebSocket [manual interaction](/usage-guides/manual-interaction) actions alongside the [video stream](/usage-guides/video-streaming).
See [Handling Guardrails](/usage-guides/handling-guardrails) for the full flow.
***
### list\_environments
List available persistent environments for the account and show which one the connection is using. Read-only. Takes no parameters.
Use it to find the `environmentId` for a persistent session. Workflows and agents use the connection's environment automatically.
***
### list\_workflows
List saved workflows — prompt-templated browser automations — with each one's title, schedule, `{{variables}}`, and run stats. Read-only.
**Parameters:**
| Parameter | Type | Required | Default | Description |
| --------- | ------ | -------- | --------------- | ----------------------------------------------------------------------------------------------------- |
| `scope` | string | No | `"environment"` | `"environment"` lists workflows in the bound environment; `"all"` lists every workflow on the account |
***
### get\_workflow
Full detail of one workflow: prompt template, variables and defaults, trigger and schedule, run settings, memory state, and any pending logins. Read-only; proxy credentials are masked.
**Parameters:** `workflowId` (24-hex ID) or `title` (exact, case-insensitive).
***
### create\_workflow
Create a new saved workflow.
**Parameters:**
| Parameter | Type | Required | Description |
| ------------------- | --------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `title` | string | Yes | Workflow title shown on the dashboard |
| `promptTemplate` | string | Yes | The task, written as a browsing runbook: `Goal:`, ground rules, one `Stage N` per site, and an `Output —` contract |
| `memoryContract` | object | Conditional | Required whenever the task must handle each item exactly once. Three plain-English fields: `groundRules`, `memoryInstruction`, `itemIdentity` |
| `startingUrl` | string | No | Page Chrome opens at the start of each run |
| `outputType` | string | No | `"text"`, `"structured"`, or `"structured_csv"` |
| `outputSchema` | object \| array | No | JSON Schema, or column names for `structured_csv` |
| `schedule` | object | No | Saved setting only — see the warning below |
| `templateVariables` | array | No | Metadata for `{{variables}}`, only for deliberately reusable templates |
| `environmentId` | string | No | Rarely needed; the connection's environment is applied automatically |
Presentation and run settings — `model`, `proxy`, `timezone`, `policyId`, `requiredFiles`, `shortDescription`, `triggerPhrase` and others — are all optional and default sensibly.
A `schedule` on a workflow is recorded as a setting only. The workflow does not run on a timer until it is deployed as a scheduled agent with [`create_agent`](#create_agent).
Write concrete values (group names, URLs, numbers) directly into `promptTemplate`. Use `{{variables}}` only for a reusable template whose inputs genuinely change per run.
***
### update\_workflow
Update an existing workflow. Supply `workflowId` (required) plus only the fields to change. Object and array fields are replaced whole; pass `null` to clear an optional field. Renaming via `title` keeps the slug stable.
`memoryContract` is the exception to whole-replacement: supplying its three fields updates them while platform tracking details are preserved.
***
### trigger\_workflow
Run a workflow now in its deployed environment. Returns a `sessionId` — poll `get_task_status` for the result.
**Parameters:**
| Parameter | Type | Required | Description |
| ------------ | ------- | ----------- | ------------------------------------------------------------------------ |
| `workflowId` | string | Conditional | 24-hex workflow ID — or use `title` |
| `title` | string | Conditional | Exact workflow title, case-insensitive |
| `variables` | object | No | Values for the workflow's `{{variables}}`, merged over stored defaults |
| `force` | boolean | No | Work-list workflows only: re-open a completed list for a fresh full pass |
This is the only correct way to run or test a saved workflow. A run started with `browser_task` or `create_session` does not carry the workflow's rules, tracking or memory, so it will behave differently.
***
### create\_agent
Create a scheduled agent — a recurring or one-time automation that runs on a timer.
**Two modes:**
| Mode | How | What happens |
| ---------- | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| Workflow | Pass `workflowId` + `schedule` | Prompt, starting URL, output contract, model, proxy, policy and files are copied from the workflow; results and memory stay centralised on it |
| Standalone | Omit `workflowId`; pass `name`, `prompt`, `schedule` | Runs on its own in the connection's environment |
**Parameters:**
| Parameter | Type | Required | Description |
| ----------------------------- | ------ | ----------- | ------------------------------------------------------------------ |
| `schedule` | object | Yes | `{ type: "at" \| "every" \| "cron", ... }` — see below |
| `workflowId` | string | Conditional | Workflow mode: the workflow to deploy |
| `name` | string | Conditional | Required standalone; defaults to the workflow title otherwise |
| `prompt` | string | Conditional | Required standalone: the browsing runbook to run |
| `variables` | object | No | Workflow mode: values baked in at deploy time and reused every run |
| `startingUrl` | string | No | Standalone: page Chrome opens each run |
| `outputType` / `outputSchema` | - | No | Standalone: output contract |
| `expiresAt` | string | No | ISO 8601 date-time after which the agent auto-pauses |
**Schedule shapes:**
| `type` | Field | Meaning |
| --------- | ---------- | ------------------------------------- |
| `"at"` | `at` | ISO 8601 date-time — fires once |
| `"every"` | `interval` | Repeat interval in ms (minimum 60000) |
| `"cron"` | `cron` | 5-field cron expression |
All three accept `timezone` (IANA name, default UTC), which drives both the fire times and the browser session.
***
### list\_agents
List the account's scheduled agents: schedule, status, next and last run, and whether each is standalone or deployed from a workflow. Read-only.
**Parameters:** `scope` — `"environment"` (default when bound) or `"all"`.
***
### pause\_agent
Pause an active scheduled agent — it stops firing until resumed.
**Parameters:** `agentId` (24-hex, required).
***
### resume\_agent
Resume a paused agent, recomputing its next run. A completed work-list agent restarts with a fresh full pass.
**Parameters:** `agentId` (24-hex, required).
`resume_agent` refuses if the agent's expiry has already passed. Extend it on the dashboard first.
***
## Advanced Patterns
### Pattern 1: Multi-Step Research Workflow
```
User: "Research wireless keyboards on Amazon. First go to Amazon, search for wireless keyboards, then tell me about the top 3 results."
Claude's execution:
1. Uses create_session:
{
"task": {
"prompt": "Go to amazon.com",
"startingUrl": "https://amazon.com"
}
}
→ Gets sessionId: "abc123"
2. Uses send_task:
{
"sessionId": "abc123",
"prompt": "Search for wireless keyboards"
}
→ Gets search results
3. Uses send_task:
{
"sessionId": "abc123",
"prompt": "Extract the names, prices, and ratings of the top 3 results",
"terminateOnCompletion": true
}
→ Gets structured data and auto-terminates
```
***
### Pattern 2: Guardrail Handling
```
User: "Log in to example.com and extract my dashboard data"
Claude's execution:
1. Uses create_session:
{
"task": {
"prompt": "Go to example.com and log in",
"startingUrl": "https://example.com"
}
}
→ Agent reaches the login form and raises a guardrail
2. Uses get_task_status:
{ "sessionId": "abc123", "taskId": "task456" }
→ Reports the agent is awaiting input
3. Claude asks the user for the one-time code
4. Uses guardrail_response:
{
"sessionId": "abc123",
"response": "The verification code is 481920",
"newState": "resume"
}
→ Agent continues
5. Uses send_task:
{
"sessionId": "abc123",
"prompt": "Extract all dashboard data",
"terminateOnCompletion": true
}
→ Completes task
```
Use an environment for sites you log into repeatedly. The session stays authenticated, so later tasks skip the login entirely.
***
### Pattern 3: Long Task with Status Monitoring
```
User: "Scrape all product listings from this marketplace (might take a while)"
Claude's execution:
1. Uses create_session, then send_task with maxDuration: 45
2. While the task runs, uses get_task_status every 30 seconds:
{
"sessionId": "abc123",
"taskId": "task456"
}
3. Reports progress to user:
"Task is still running. So far used 15,000 tokens, cost: $0.012"
4. When status changes to "completed", retrieves final result
```
***
### Pattern 4: Inspect, Then Correct
```
User: "Go to example.com and extract all links"
Claude's execution:
1. Uses create_session with the task
→ Result looks wrong: far fewer links than expected
2. Uses screenshot:
{ "sessionId": "abc123" }
→ Sees a cookie banner covering the page
3. Uses send_task:
{
"sessionId": "abc123",
"prompt": "Dismiss the cookie banner, then extract all links",
"terminateOnCompletion": true
}
→ Succeeds
```
***
### Pattern 5: Run a Saved Workflow on a Schedule
```
User: "Run my 'Daily competitor prices' workflow every weekday at 8am UK time."
Claude's execution:
1. Uses list_workflows to find it
→ workflowId: "65f0a1b2c3d4e5f60718293b"
2. Uses trigger_workflow once to check it works:
{ "workflowId": "65f0a1b2c3d4e5f60718293b" }
→ Polls get_task_status for the result
3. Uses create_agent to put it on a timer:
{
"workflowId": "65f0a1b2c3d4e5f60718293b",
"schedule": { "type": "cron", "cron": "0 8 * * 1-5", "timezone": "Europe/London" }
}
```
***
## Troubleshooting
### Tools Not Appearing
**Symptoms:** MCP tools don't show up, or no browser automation options are available.
**Solutions:**
1. **Claude Code:** run `claude mcp get webrun`. The most common cause is a missing `"type": "http"` — without it the entry is treated as a local command.
2. **Cursor and VS Code:** confirm the top-level key. Cursor uses `mcpServers`, VS Code uses `servers`.
3. **Cline:** confirm `"type": "streamableHttp"` — camelCase, no hyphen. `streamable-http` or a missing `type` falls back to SSE and fails with a 405.
4. **Claude Desktop:** the config file only accepts local (stdio) servers. Use **Settings → Connectors**, or bridge with `mcp-remote` as shown above.
5. **Check JSON syntax:**
```bash theme={null}
cat .mcp.json | jq .
# Should output valid JSON without errors
```
6. **Claude Desktop logs:**
* macOS: `~/Library/Logs/Claude/mcp*.log`
* Windows: `%APPDATA%\Claude\logs\mcp*.log`
Claude Code, Cursor and VS Code pick up config changes without a restart. Only Claude Desktop needs a full quit and reopen.
***
### It Connects but Every Task Fails
The server lists its tools without a key, so a connection with a missing or wrong key looks perfectly healthy until the first task runs.
**Solutions:**
1. **Check the header name and value.** It is `API-Key`, and the value is the key on its own — no `Bearer` prefix.
2. **Confirm the key is active:** open the dashboard, check the key exists and has not been revoked, and generate a new one if needed.
3. **Check the account has balance.**
4. **Test the key against the REST API:**
```bash theme={null}
curl -X POST https://api.webrun.ai/start/run-task \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"task": {"prompt": "Go to google.com"}}'
# Should return success, not 401
```
***
### Authentication Errors
**Error:** `"Invalid API key"` or `"Unauthorized"`
Keys start with `wr_` or `enig_`. Confirm the key is active in the dashboard and that the account has balance. Check for stray spaces or quotes around the header value.
***
### "Environment not found"
The `Environment-Id` must be a 24-character hex string belonging to your account. Ask the assistant to list your environments, or copy the ID from the Environment page in the dashboard.
If you meant to run on a disposable machine, remove the header entirely rather than leaving it blank.
***
### Session Timeout Errors
**Error:** `"Session not found"` or `"Session expired"`
**Cause:** sessions expire after **5 minutes of inactivity** (fixed, not configurable). Separately, a single task runs for up to **20 minutes** by default.
**Solutions:**
1. **Raise the task cap** — pass `maxDuration` in minutes, up to 60:
```json theme={null}
{
"sessionId": "abc123",
"prompt": "Complex task",
"maxDuration": 45
}
```
2. **Break long work into chunks:**
```
// Bad: One huge task
"Extract data from all 100 pages"
// Good: Chunked tasks
"Extract data from pages 1-10"
"Extract data from pages 11-20"
```
3. **Use `get_task_status`** to check progress and detect stalls early.
***
### Task Failures
**Error:** `"Navigation timeout"`, `"Element not found"`, etc.
**Solutions:**
1. **Make instructions more specific:**
```
// Vague
"Get the price"
// Specific
"Find the product price displayed near the 'Add to Cart' button"
```
2. **Use `screenshot`** to see what the agent sees before guessing at a fix.
3. **Use `startingUrl` for known websites:**
```json theme={null}
{
"prompt": "Search for wireless keyboards",
"startingUrl": "https://amazon.com"
}
```
4. **Check for CAPTCHAs or login requirements** — answer with `guardrail_response`, or use an environment that is already logged in.
***
## Tool Parameter Reference
### Quick Reference Table
| Tool | Required Parameters | Key Optional Parameters |
| --------------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `browser_task` | `prompt` | `startingUrl`, `environmentId`, `maxDuration`, `outputType`, `outputSchema`, `files`, `secrets`, `proxy`, `policyId`, `model`, `timezone`, `webhook`, `reach_out_mode` |
| `create_session` | - | `task`, `environmentId`, `mode`, `model`, `policyId`, `proxy`, `timezone`, `reach_out_mode` |
| `send_task` | `sessionId`, `prompt` | `startingUrl`, `maxDuration`, `maxInputTokens`, `maxOutputTokens`, `outputType`, `outputSchema`, `files`, `secrets`, `terminateOnCompletion`, `webhook` |
| `get_task_status` | `sessionId`, `taskId` | - |
| `screenshot` | `sessionId` | - |
| `list_sessions` | - | - |
| `terminate_session` | `sessionId` | - |
| `pause_session_task` | `sessionId` | - |
| `resume_session_task` | `sessionId` | - |
| `stop_session_task` | `sessionId` | - |
| `guardrail_response` | `sessionId` | `response`, `newState`, `files` |
| `list_environments` | - | - |
| `list_workflows` | - | `scope` |
| `get_workflow` | `workflowId` or `title` | - |
| `create_workflow` | `title`, `promptTemplate` | `memoryContract`, `startingUrl`, `outputType`, `outputSchema`, `schedule`, `templateVariables` |
| `update_workflow` | `workflowId` | any field to change |
| `trigger_workflow` | `workflowId` or `title` | `variables`, `force` |
| `create_agent` | `schedule` | `workflowId`, `name`, `prompt`, `variables`, `startingUrl`, `expiresAt` |
| `list_agents` | - | `scope` |
| `pause_agent` | `agentId` | - |
| `resume_agent` | `agentId` | - |
### Parameter Details
**prompt** (string)
* Natural language description of the task
* Be specific for better results
* Good: "Search Google for 'Anthropic' and summarize the first result"
* Good: "Extract all product names and prices from this page"
* Avoid: "Search" (too vague)
**startingUrl** (string)
* Must be a valid HTTP/HTTPS URL
* Optional, but speeds up navigation compared to "go to amazon.com"
**environmentId** (string)
* Optional. 24-character hex ID of a persistent environment
* Overrides the connection's `Environment-Id` header for this one call
* Omit it on a connection with no environment and the task runs on its own temporary browser, discarded when the task ends
**maxDuration** (number)
* Maximum task duration **in minutes**
* Default: 20 · Maximum: 60 · On `send_task`, minimum 3
* Examples: `10` = 10 minutes, `45` = 45 minutes
The MCP tools take `maxDuration` in **minutes**. The [REST API](/api-reference/parameters#maxduration) takes the same parameter in milliseconds — do not copy a value from one to the other.
**sessionId** (string)
* Returned from `create_session`, `browser_task` and `trigger_workflow`
**taskId** (string)
* Returned from task execution, and required by `get_task_status`
**terminateOnCompletion** (boolean)
* `true`: auto-close the session after the task completes
* `false` (default): keep the session alive for follow-up tasks
**newState** (string, `guardrail_response`)
* `"resume"` (default): provides the requested input and continues the task. `response` is required
* `"deny"`: declines the request. `response` is optional
**outputType** (string) and **outputSchema**
* `"text"` (default), `"structured_json"`, or `"structured_csv"`
* `outputSchema` is required for `"structured_json"` — see [Structured Output](/usage-guides/structured-output)
**reach\_out\_mode** (string)
* Controls proactive chat messages to a user (Telegram, WhatsApp, Slack, Discord, Teams) connected to the same environment when no one is watching the session live
* `"off"` (default): no proactive messages — guardrails and results stay on the MCP channel only. Best for sessions handling private data
* `"guardrail_only"`: pings the chat user on guardrails (CAPTCHA, 2FA, verification, login) when the API caller is offline
* `"full"`: pings on guardrails **and** delivers the task result on completion
* Available on `browser_task` and `create_session`. Each bot user additionally filters by their own preference
* See [Routing Guardrails to a Chat User](/usage-guides/handling-guardrails#routing-guardrails-to-a-chat-user)
***
## Best Practices
### 1. Session Management
**Do:**
* Use `browser_task` for one-off tasks
* Use `create_session` + `send_task` for multi-step workflows
* Use `trigger_workflow` — never `browser_task` — to run or test a saved workflow
* Always set `terminateOnCompletion: true` on your final task
* Terminate sessions explicitly with `terminate_session` when done
**Don't:**
* Create multiple sessions for related tasks
* Leave sessions running after completion
* Use `create_session` for simple one-off tasks
***
### 2. Task Instructions
**Do:**
* Be specific and detailed
* Include the expected output format
* Specify wait conditions if needed
* Provide starting URLs when known
**Don't:**
* Use vague instructions like "get data"
* Assume the agent knows which element to click
* Skip important context
***
### 3. Error Handling
**Do:**
* Monitor long tasks with `get_task_status`
* Use `screenshot` to see the real page state before retrying
* Answer CAPTCHAs and 2FA prompts with `guardrail_response`
* Raise `maxDuration` (in minutes) rather than letting a long task be cut off
**Don't:**
* Ignore timeout warnings
* Retry indefinitely without changes
* Assume tasks will always succeed
***
### 4. Cost Optimization
**Do:**
* Terminate sessions when done
* Use `terminateOnCompletion` on final tasks
* Break very long tasks into chunks
* Reuse sessions for related tasks
**Don't:**
* Leave sessions idle
* Create new sessions for each small task
* Ignore session timeout warnings
***
Connect Claude, ChatGPT, Claude Code, Cursor, VS Code or Cline
Build complex automation sequences
Respond to human-in-the-loop requests
Persistent machines that keep logins and files
# OpenAI-Compatible API
Source: https://docs.webrun.ai/integrations/openai-compatible
Use WebRun with OpenAI SDK, LangChain, LlamaIndex, and Vercel AI SDK
## When to Use OpenAI-Compatible Endpoint
The OpenAI-compatible API is ideal when:
* You're migrating from OpenAI and want minimal code changes
* You're using frameworks built for OpenAI (LangChain, LlamaIndex, Vercel AI SDK)
* You want a simple chat interface for browser automation
* You need streaming responses
* You prefer the familiar OpenAI SDK patterns
**Choose native REST/WebSocket instead if you need:**
* Multi-task sessions with persistent browser state
* Manual browser control and takeover
* Video streaming
* Fine-grained session management
The OpenAI-compatible endpoint creates a new session for each request and auto-terminates after completion. For multi-task workflows, use the native REST API.
***
## Setup with OpenAI SDK
### Installation
```bash theme={null}
npm install openai
```
### Basic Usage
```javascript theme={null}
import OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'https://api.webrun.ai/v1',
apiKey: 'YOUR_API_KEY' // Your WebRun API key
});
const completion = await client.chat.completions.create({
model: 'webrun-browser-1',
messages: [
{ role: 'user', content: 'Go to google.com and search for Anthropic' }
]
});
console.log(completion.choices[0].message.content);
```
**Response:**
```json theme={null}
{
"id": "chatcmpl-a1b2c3d4",
"object": "chat.completion",
"created": 1704067200,
"model": "webrun-browser-1",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Successfully searched for Anthropic on Google. The first result is the official Anthropic website at anthropic.com, which describes Claude as a next-generation AI assistant..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650
}
}
```
***
## Framework Examples
### LangChain
```javascript theme={null}
import { ChatOpenAI } from "@langchain/openai";
import { HumanMessage } from "@langchain/core/messages";
const model = new ChatOpenAI({
modelName: "webrun-browser-1",
openAIApiKey: "YOUR_API_KEY",
configuration: {
baseURL: "https://api.webrun.ai/v1"
}
});
const response = await model.invoke([
new HumanMessage("Go to amazon.com and search for wireless keyboards. List the top 3 results with prices.")
]);
console.log(response.content);
```
**With Streaming:**
```javascript theme={null}
const stream = await model.stream([
new HumanMessage("Search Google for Anthropic and summarize the first result")
]);
for await (const chunk of stream) {
process.stdout.write(chunk.content);
}
```
**With Chains:**
```javascript theme={null}
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";
const model = new ChatOpenAI({
modelName: "webrun-browser-1",
openAIApiKey: "YOUR_API_KEY",
configuration: {
baseURL: "https://api.webrun.ai/v1"
}
});
const prompt = ChatPromptTemplate.fromMessages([
["system", "You are a web research assistant. Extract structured data from websites."],
["human", "{task}"]
]);
const chain = prompt.pipe(model).pipe(new StringOutputParser());
const result = await chain.invoke({
task: "Go to example.com and extract all product names and prices"
});
console.log(result);
```
***
### LlamaIndex
```javascript theme={null}
import { OpenAI } from "llamaindex";
const llm = new OpenAI({
model: "webrun-browser-1",
apiKey: "YOUR_API_KEY",
additionalChatOptions: {
baseURL: "https://api.webrun.ai/v1"
}
});
const response = await llm.chat({
messages: [
{
role: "user",
content: "Navigate to github.com/anthropics and list the top 5 repositories"
}
]
});
console.log(response.message.content);
```
**With Agent:**
```javascript theme={null}
import { OpenAI, OpenAIAgent } from "llamaindex";
const llm = new OpenAI({
model: "webrun-browser-1",
apiKey: "YOUR_API_KEY",
additionalChatOptions: {
baseURL: "https://api.webrun.ai/v1"
}
});
const agent = new OpenAIAgent({
llm,
systemPrompt: "You are a browser automation assistant. Help users extract data from websites."
});
const response = await agent.chat({
message: "Go to product hunt and find the top 3 products today"
});
console.log(response.response);
```
***
### Vercel AI SDK
```javascript theme={null}
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';
const model = openai('webrun-browser-1', {
baseURL: 'https://api.webrun.ai/v1',
apiKey: 'YOUR_API_KEY'
});
const { text } = await generateText({
model,
prompt: 'Go to news.ycombinator.com and summarize the top 5 stories'
});
console.log(text);
```
**With Streaming:**
```javascript theme={null}
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
const model = openai('webrun-browser-1', {
baseURL: 'https://api.webrun.ai/v1',
apiKey: 'YOUR_API_KEY'
});
const { textStream } = await streamText({
model,
prompt: 'Search Google for "AI browser automation" and summarize the results'
});
for await (const textPart of textStream) {
process.stdout.write(textPart);
}
```
**In Next.js Route Handler:**
```javascript theme={null}
// app/api/research/route.ts
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
export async function POST(req: Request) {
const { task } = await req.json();
const model = openai('webrun-browser-1', {
baseURL: 'https://api.webrun.ai/v1',
apiKey: process.env.WEBRUN_API_KEY
});
const result = await streamText({
model,
prompt: task
});
return result.toAIStreamResponse();
}
// Usage in component:
// const response = await fetch('/api/research', {
// method: 'POST',
// body: JSON.stringify({ task: 'Go to example.com and extract all links' })
// });
```
***
## Chat Completions Format
### Request Format
```bash theme={null}
POST https://api.webrun.ai/v1/chat/completions
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY
```
```json theme={null}
{
"model": "webrun-browser-1",
"messages": [
{
"role": "system",
"content": "You are a helpful browser automation assistant."
},
{
"role": "user",
"content": "Go to example.com and extract all headings"
}
],
"stream": false,
"max_tokens": 2000
}
```
**Parameters:**
| Parameter | Type | Required | Description |
| ---------------- | ------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `model` | string | Yes | Must be `"webrun-browser-1"` |
| `messages` | array | Yes | Array of message objects with `role` and `content` |
| `stream` | boolean | No | Enable streaming responses (default: false) |
| `max_tokens` | number | No | Maximum tokens in response (default: 2000) |
| `reach_out_mode` | string | No | Controls proactive chat messages to a user (Telegram/WhatsApp/Slack/Discord/Teams) connected to the underlying session's environment. One of `"off"` (no messages), `"guardrail_only"` (only on guardrails), or `"full"` (guardrails plus task results). Default: `"guardrail_only"`. See [Routing Guardrails to a Chat User](/usage-guides/handling-guardrails#routing-guardrails-to-a-chat-user) |
| `temperature` | number | No | Not used (included for compatibility) |
***
### Non-Streaming Response
```json theme={null}
{
"id": "chatcmpl-a1b2c3d4e5f6",
"object": "chat.completion",
"created": 1704067200,
"model": "webrun-browser-1",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "I found 5 headings on example.com:\n1. Example Domain\n2. More Information\n3. Contact\n4. About\n5. Privacy Policy"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 8450,
"completion_tokens": 2100,
"total_tokens": 10550
},
"webrun": {
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"cost": 0.0089
}
}
```
***
### Streaming Response
When `stream: true`, responses use Server-Sent Events (SSE):
```
data: {"id":"chatcmpl-a1b2c3","object":"chat.completion.chunk","created":1704067200,"model":"webrun-browser-1","choices":[{"index":0,"delta":{"role":"assistant","content":"I"},"finish_reason":null}]}
data: {"id":"chatcmpl-a1b2c3","object":"chat.completion.chunk","created":1704067200,"model":"webrun-browser-1","choices":[{"index":0,"delta":{"content":" found"},"finish_reason":null}]}
data: {"id":"chatcmpl-a1b2c3","object":"chat.completion.chunk","created":1704067200,"model":"webrun-browser-1","choices":[{"index":0,"delta":{"content":" 5"},"finish_reason":null}]}
...
data: {"id":"chatcmpl-a1b2c3","object":"chat.completion.chunk","created":1704067200,"model":"webrun-browser-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
```
**Handling Streams:**
```javascript theme={null}
import OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'https://api.webrun.ai/v1',
apiKey: 'YOUR_API_KEY'
});
const stream = await client.chat.completions.create({
model: 'webrun-browser-1',
messages: [
{ role: 'user', content: 'Go to news.ycombinator.com and summarize top stories' }
],
stream: true
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}
```
***
## Available Models
| Model Name | Description |
| ------------------ | ---------------------------------------------------- |
| `webrun-browser-1` | Default browser automation model (Claude Sonnet 3.5) |
Currently, only `webrun-browser-1` is available. Additional models may be added in the future.
***
## Differences from Standard OpenAI API
### Supported Features
* Chat completions endpoint
* Streaming responses
* Message history
* System messages
* Token usage reporting
### Not Supported
* Function calling (use native REST API for manual control)
* Vision (images in messages)
* Tool use (use native REST API for multi-task workflows)
* Fine-tuning
* Embeddings
* Moderation
* Audio/Speech
* Temperature/top\_p (task execution is deterministic)
### Different Behavior
**1. Session Management**
* OpenAI: Stateless, each request is independent
* WebRun: Each request creates a new browser session that auto-terminates
**2. Response Time**
* OpenAI: Typically 1-5 seconds
* WebRun: Typically 10-50 seconds (real browser automation)
**3. Context Window**
* OpenAI: Based on model (e.g., 128k tokens)
* WebRun: Task-focused, less emphasis on large context
**4. Pricing**
* OpenAI: Per-token pricing
* WebRun: Per-task pricing with token usage included in response
***
## Limitations
### Multi-Task Workflows
The OpenAI-compatible endpoint creates a new session per request. For multi-step workflows, use the native REST API:
```javascript theme={null}
// OpenAI-compatible - Each request is a new session
const completion1 = await client.chat.completions.create({
model: 'webrun-browser-1',
messages: [{ role: 'user', content: 'Go to amazon.com' }]
});
const completion2 = await client.chat.completions.create({
model: 'webrun-browser-1',
messages: [{ role: 'user', content: 'Search for keyboards' }] // New session, not on Amazon
});
// Native REST API - Persistent session
const session = await fetch('https://api.webrun.ai/start/start-session', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({ task: { prompt: 'Go to amazon.com' } })
}).then(r => r.json());
await fetch('https://api.webrun.ai/start/send-message', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
sessionId: session.sessionId,
message: {
actionType: 'newTask',
newState: 'start',
prompt: 'Search for keyboards' // Same session, still on Amazon
}
})
});
```
***
### Guardrails
Guardrails (human-in-the-loop) are not supported via OpenAI-compatible endpoint. If a guardrail triggers, the request will fail:
```json theme={null}
{
"error": {
"message": "Guardrail triggered: I need login credentials to proceed",
"type": "guardrail_error",
"code": "guardrail_triggered"
}
}
```
**Solution:** Use native REST or WebSocket API for guardrail handling.
***
### Video Streaming
Live video streaming is not available via OpenAI-compatible endpoint. Use native REST API to get `webRTCURL` and `webViewURL`.
***
## Complete Example: Research Assistant
```javascript theme={null}
import OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'https://api.webrun.ai/v1',
apiKey: process.env.WEBRUN_API_KEY
});
async function researchTopic(topic) {
console.log(`Researching: ${topic}`);
const completion = await client.chat.completions.create({
model: 'webrun-browser-1',
messages: [
{
role: 'system',
content: 'You are a research assistant. Search the web and provide concise, factual summaries.'
},
{
role: 'user',
content: `Search Google for "${topic}" and summarize the top 3 results in a structured format.`
}
],
stream: false
});
const result = completion.choices[0].message.content;
const usage = completion.usage;
const cost = completion.webrun?.cost || 0;
console.log('\n--- Results ---');
console.log(result);
console.log('\n--- Usage ---');
console.log(`Tokens: ${usage.total_tokens} (${usage.prompt_tokens} prompt + ${usage.completion_tokens} completion)`);
console.log(`Cost: $${cost}`);
return result;
}
// Usage
await researchTopic('Claude AI capabilities');
await researchTopic('Browser automation with AI agents');
```
***
## Error Handling
```javascript theme={null}
import OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'https://api.webrun.ai/v1',
apiKey: 'YOUR_API_KEY'
});
async function safeCompletion(prompt) {
try {
const completion = await client.chat.completions.create({
model: 'webrun-browser-1',
messages: [{ role: 'user', content: prompt }]
});
return completion.choices[0].message.content;
} catch (error) {
if (error.status === 401) {
console.error('Invalid API key');
} else if (error.status === 402) {
console.error('Insufficient balance');
} else if (error.status === 429) {
console.error('Rate limit exceeded');
} else if (error.status === 503) {
console.error('No browser instances available');
} else if (error.code === 'guardrail_triggered') {
console.error('Guardrail triggered:', error.message);
// Use native API for guardrail handling
} else {
console.error('Unexpected error:', error.message);
}
throw error;
}
}
```
***
Full control with native REST API
Real-time events and live updates
# REST API Integration
Source: https://docs.webrun.ai/integrations/rest-api
Build browser automation with WebRun's REST API endpoints
## When to Use REST API
The REST API is ideal for:
* **Serverless environments** (AWS Lambda, Vercel, Cloudflare Workers)
* **Simple integrations** where you don't need real-time events
* **Stateless workflows** that poll for results
* **Backend services** that trigger automation tasks
* **Workflow automation** (n8n, Make.com, Zapier)
**Choose WebSocket instead if you need:**
* Live agent thoughts and reasoning
* Sub-second event notifications
* Real-time UI updates
***
## Authentication
All API requests require Bearer token authentication:
```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```
Get your API key at [webrun.ai/settings](https://webrun.ai/settings)
**Base URL:**
```
https://api.webrun.ai
```
***
## Basic Patterns
### Pattern 1: Single Task (run-task)
The simplest pattern for one-off tasks. Session auto-terminates after completion.
```bash theme={null}
curl -X POST https://api.webrun.ai/start/run-task \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"task": {
"prompt": "Go to google.com and search for Anthropic"
}
}'
```
**Response (completed within 50 seconds):**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"type": "task_completed",
"data": {
"message": "Successfully searched for Anthropic on Google",
"files": [],
"network": [
{
"id": "tevo9",
"taskId": "x9y8z7w6v5u4",
"urls": [
{
"url": "https://www.google.com/search?q=Anthropic",
"timestamp": 1771138379087.646
}
]
}
]
},
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"completion_time": 23.5,
"cost": 0.0124
}
}
```
**Response (still running after 50 seconds):**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"status": "pending",
"pollUrl": "https://api.webrun.ai/task/a1b2c3d4e5f6/x9y8z7w6v5u4",
"message": "Task still running. Poll GET /task/:sessionId/:taskId for result."
}
```
Most browser tasks complete in 10-40 seconds. The API waits up to 50 seconds before responding, so typical requests return results immediately: no polling required.
***
### Pattern 2: Multi-Task Session
For workflows that require multiple sequential tasks in the same browser session.
**Step 1: Create persistent session**
```bash theme={null}
curl -X POST https://api.webrun.ai/start/start-session \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"mode": "default",
"task": {
"prompt": "Go to amazon.com",
"startingUrl": "https://amazon.com"
}
}'
```
**Response:**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"socketURL": "https://api.webrun.ai",
"streaming": {
"webRTCURL": "https://a1b2c3d4e5f6.webrun.ai/whep",
"webViewURL": "https://a1b2c3d4e5f6.webrun.ai",
"dimensions": { "width": 1024, "height": 600 }
},
"expiresIn": 300000,
"balance": 12.50
}
```
**Step 2: Send follow-up task**
```bash theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "a1b2c3d4e5f6",
"message": {
"actionType": "newTask",
"newState": "start",
"prompt": "Search for wireless keyboards",
"terminateOnCompletion": true
}
}'
```
**Cost Tip:** Set `terminateOnCompletion: true` on your last task to auto-close the session and avoid idle charges. Sessions remain billable until terminated or timed out.
***
### Pattern 3: Polling for Results
When a task returns `status: "pending"`, poll until completion:
```javascript theme={null}
async function runTask(prompt, apiKey) {
const response = await fetch("https://api.webrun.ai/start/run-task", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({ task: { prompt } })
});
const data = await response.json();
// Inline result - return immediately
if (data.status === "complete") {
return data.result;
}
// Pending - poll for result
if (data.status === "pending") {
return await pollForResult(data.sessionId, data.taskId, apiKey);
}
throw new Error(data.message || "Task failed");
}
async function pollForResult(sessionId, taskId, apiKey) {
const maxAttempts = 60; // 2 minutes max
const interval = 2000; // Poll every 2 seconds
for (let i = 0; i < maxAttempts; i++) {
const res = await fetch(
`https://api.webrun.ai/task/${sessionId}/${taskId}`,
{ headers: { "Authorization": `Bearer ${apiKey}` } }
);
const data = await res.json();
if (data.type === "task_completed") return data;
if (data.type === "guardrail_trigger") return data;
if (!data.success && data.status === "failed") throw new Error(data.error);
// Still running - wait and retry
await new Promise(r => setTimeout(r, interval));
}
throw new Error("Task timeout after 2 minutes");
}
// Usage
const result = await runTask("Search Google for Anthropic", "wr_xxx");
console.log(result.data.message);
console.log(`Cost: $${result.usage.cost}`);
```
***
## Complete Examples
### Example 1: Simple Task Execution
```javascript theme={null}
const API_KEY = "wr_xxxxxxxxxxxx";
async function searchGoogle(query) {
const response = await fetch("https://api.webrun.ai/start/run-task", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
task: {
prompt: `Search Google for "${query}" and summarize the first result`
}
})
});
const data = await response.json();
if (data.status === "complete") {
return data.result.data.message;
} else if (data.status === "pending") {
// Poll for result
const result = await pollForResult(data.sessionId, data.taskId, API_KEY);
return result.data.message;
}
throw new Error(data.message || "Task failed");
}
// Usage
const summary = await searchGoogle("Anthropic Claude");
console.log(summary);
```
***
### Example 2: Multi-Step Workflow
```javascript theme={null}
const API_KEY = "wr_xxxxxxxxxxxx";
const BASE = "https://api.webrun.ai";
async function amazonProductResearch(productName) {
// 1. Create session
const session = await fetch(`${BASE}/start/start-session`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
mode: "default",
task: {
prompt: "Go to amazon.com",
startingUrl: "https://amazon.com"
}
})
}).then(r => r.json());
const sessionId = session.sessionId;
// 2. Search for product
const searchTask = await fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId,
message: {
actionType: "newTask",
newState: "start",
prompt: `Search for "${productName}" and list the top 3 results with prices`
}
})
}).then(r => r.json());
// Poll if needed
let searchResult;
if (searchTask.pending) {
searchResult = await pollForResult(sessionId, searchTask.taskId, API_KEY);
} else {
searchResult = searchTask.result;
}
console.log("Search results:", searchResult.data.message);
// 3. Add first item to cart
const cartTask = await fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId,
message: {
actionType: "newTask",
newState: "start",
prompt: "Add the first product to cart",
terminateOnCompletion: true // Auto-close session
}
})
}).then(r => r.json());
// Poll if needed
let cartResult;
if (cartTask.pending) {
cartResult = await pollForResult(sessionId, cartTask.taskId, API_KEY);
} else {
cartResult = cartTask.result;
}
return {
searchResults: searchResult.data.message,
cartStatus: cartResult.data.message
};
}
// Usage
const results = await amazonProductResearch("wireless keyboard");
console.log(results);
```
***
### Example 3: Using a Proxy
Route traffic through a proxy for geographic targeting or IP management. The `proxy` field is top-level, alongside `environmentId`:
```javascript theme={null}
const API_KEY = "wr_xxxxxxxxxxxx";
// WebRun-managed proxy (specify country)
const response = await fetch("https://api.webrun.ai/start/run-task", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
task: {
prompt: "Check product prices on amazon.co.uk",
startingUrl: "https://amazon.co.uk"
},
proxy: {
source: "WebRun",
country: "GB"
}
})
});
const data = await response.json();
console.log(data);
```
See the [Proxies guide](/usage-guides/proxies) for custom proxy configuration and best practices.
***
### Example 4: Using an Environment
Attach an [environment](/environments/overview) to reuse saved cookies and login sessions across tasks:
```javascript theme={null}
const API_KEY = "wr_xxxxxxxxxxxx";
async function runWithEnvironment(environmentId, prompt) {
const response = await fetch("https://api.webrun.ai/start/run-task", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
environmentId,
task: { prompt }
})
});
return response.json();
}
// First run: log in and save cookies to the environment's profile
await runWithEnvironment("", "Go to amazon.com and log in");
// Subsequent runs: environment has saved cookies, no login needed
const result = await runWithEnvironment(
"",
"Go to amazon.com and check my recent orders"
);
console.log(result);
```
***
### Example 5: Authenticated Task with Secrets
Use [secrets](/usage-guides/secrets) to provide credentials upfront so the agent can authenticate without guardrail interruptions:
```javascript theme={null}
async function loginAndExtractWithSecrets(url) {
const BASE = "https://api.webrun.ai";
const API_KEY = "wr_xxxxxxxxxxxx";
const session = await fetch(`${BASE}/start/start-session`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
mode: "default",
task: {
prompt: `Go to ${url}, log in, and extract all user data from the dashboard`,
startingUrl: url,
terminateOnCompletion: true,
secrets: [
{
match: `*.${new URL(url).hostname}`,
fields: {
email: process.env.SITE_EMAIL,
password: process.env.SITE_PASSWORD
}
}
]
}
})
}).then(r => r.json());
// Poll for result, no guardrail handling needed
const taskId = session.taskId || session.sessionId;
return await pollForResult(session.sessionId, taskId, API_KEY);
}
```
***
### Example 6: Handling Guardrails
```javascript theme={null}
async function loginAndExtractData(url, credentials) {
const BASE = "https://api.webrun.ai";
const API_KEY = "wr_xxxxxxxxxxxx";
// Create session with login task
const session = await fetch(`${BASE}/start/start-session`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
mode: "default",
task: {
prompt: `Go to ${url} and log in`,
startingUrl: url
}
})
}).then(r => r.json());
const sessionId = session.sessionId;
// Start login task
const loginTask = await fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId,
message: {
actionType: "newTask",
newState: "start",
prompt: "Log in to the website"
}
})
}).then(r => r.json());
// Poll for result
const taskId = loginTask.taskId;
let result = await pollForResult(sessionId, taskId, API_KEY);
// Handle guardrail if triggered
if (result.type === "guardrail_trigger") {
console.log("Guardrail:", result.data.value);
// Provide credentials
await fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId,
message: {
actionType: "guardrail",
prompt: `Username: ${credentials.username}, Password: ${credentials.password}`,
newState: "resume"
}
})
});
// Continue polling
result = await pollForResult(sessionId, taskId, API_KEY);
}
// Extract data after login
const extractTask = await fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId,
message: {
actionType: "newTask",
newState: "start",
prompt: "Extract all user data from the dashboard",
terminateOnCompletion: true
}
})
}).then(r => r.json());
if (extractTask.pending) {
return await pollForResult(sessionId, extractTask.taskId, API_KEY);
}
return extractTask.result;
}
```
***
## Session Control
Control task execution with state commands:
### Pause Task
```bash theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "a1b2c3d4e5f6",
"message": { "actionType": "state", "newState": "pause" }
}'
```
### Resume Task
```bash theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "a1b2c3d4e5f6",
"message": { "actionType": "state", "newState": "resume" }
}'
```
### Stop Task
```bash theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "a1b2c3d4e5f6",
"message": { "actionType": "state", "newState": "stop" }
}'
```
### Terminate Session
```bash theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "a1b2c3d4e5f6",
"message": { "actionType": "state", "newState": "terminate" }
}'
```
***
## Error Handling
All errors follow this format:
```json theme={null}
{
"success": false,
"message": "Human-readable error message",
"code": "ERROR_CODE"
}
```
### Common Error Codes
| Status | Code | Solution |
| ------ | ------------------------ | -------------------------- |
| 400 | `INVALID_PARAMS` | Check request parameters |
| 401 | `INVALID_API_KEY` | Verify API key is correct |
| 402 | `INSUFFICIENT_BALANCE` | Add funds to account |
| 404 | `SESSION_NOT_FOUND` | Session expired or invalid |
| 429 | `RATE_LIMIT_EXCEEDED` | Wait before retrying |
| 503 | `NO_INSTANCES_AVAILABLE` | Retry in a few moments |
### Error Handling Example
```javascript theme={null}
async function executeTaskWithRetry(prompt, apiKey, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch("https://api.webrun.ai/start/run-task", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({ task: { prompt } })
});
const data = await response.json();
if (!response.ok) {
// Handle specific error codes
if (response.status === 503) {
console.log(`Attempt ${attempt}: No instances available, retrying...`);
await new Promise(r => setTimeout(r, 2000 * attempt));
continue;
}
if (response.status === 429) {
console.log(`Attempt ${attempt}: Rate limited, waiting...`);
await new Promise(r => setTimeout(r, 5000 * attempt));
continue;
}
throw new Error(`HTTP ${response.status}: ${data.message}`);
}
return data;
} catch (error) {
if (attempt === maxRetries) throw error;
console.error(`Attempt ${attempt} failed:`, error.message);
}
}
}
```
***
Real-time events and live updates
Complete endpoint documentation
Persist browser data and files across sessions
Upload files for the agent to use in sessions
# WebSocket Integration
Source: https://docs.webrun.ai/integrations/websocket
Real-time browser automation with Socket.IO events
## When to Use WebSocket vs REST
### Use WebSocket When:
* You need **live agent thoughts and reasoning** as tasks execute
* Building **real-time dashboards** or interactive UIs
* You want **sub-second event notifications**
* You need **immediate guardrail detection**
* Building applications where users watch tasks execute live
### Use REST API When:
* Simple integrations where polling is acceptable
* Serverless environments (Lambda, Vercel)
* Stateless workflows
* You don't need real-time updates
**Rule of thumb:** If you're building a UI where users watch tasks execute, use WebSocket. Otherwise, REST is simpler.
***
## Socket.IO Setup and Connection
### Installation
```bash theme={null}
npm install socket.io-client
```
### Basic Connection
```javascript theme={null}
import { io } from "socket.io-client";
// Step 1: Create a session via REST API
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY"
},
body: JSON.stringify({
task: {
prompt: "Go to google.com and search for Anthropic"
}
})
}).then(r => r.json());
// Step 2: Connect to WebSocket with sessionId
const socket = io("https://api.webrun.ai", {
auth: { sessionId: session.sessionId },
transports: ["websocket"]
});
// Step 3: Listen for events
socket.on("connect", () => {
console.log("Connected to session");
});
socket.on("message", (data) => {
console.log("Event:", data.type, data);
});
socket.on("disconnect", () => {
console.log("Disconnected");
});
```
***
## Event Types
### agent
Live agent thoughts and reasoning as the task executes.
**Event:**
```json theme={null}
{
"type": "agent",
"content": "I'll navigate to the search box and enter the query..."
}
```
**Handler:**
```javascript theme={null}
socket.on("message", (data) => {
if (data.type === "agent") {
console.log("Agent:", data.content);
}
});
```
***
### action
Browser action performed by the agent.
**Event:**
```json theme={null}
{
"type": "action",
"data": {
"name": "click_element",
"target": "search button"
}
}
```
**Handler:**
```javascript theme={null}
socket.on("message", (data) => {
if (data.type === "action") {
console.log("Action:", data.data.name);
}
});
```
***
### task\_completed
Task finished successfully.
**Event:**
```json theme={null}
{
"type": "task_completed",
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"data": {
"message": "Successfully searched for Anthropic on Google",
"files": [
{
"source": "https://example.com/report.zip",
"downloadUrl": "https://blobs.webrun.ai/files/report.zip",
"filename": "report.zip",
"timestamp": 1771138379108
}
],
"network": [
{
"id": "tevo9",
"taskId": "x9y8z7w6v5u4",
"urls": [
{
"url": "https://www.google.com/search?q=Anthropic",
"timestamp": 1771138379087.646
}
]
}
]
},
"usage": {
"prompt_tokens": 15420,
"completion_tokens": 8230,
"total_tokens": 23650,
"completion_time": 45.3,
"cost": 0.0234
}
}
```
**Handler:**
```javascript theme={null}
socket.on("message", (data) => {
if (data.type === "task_completed") {
console.log("Done:", data.data.message);
console.log("Cost:", data.usage.cost);
if (data.data.files?.length) {
console.log("Files:", data.data.files.map(f => f.downloadUrl));
}
if (data.data.network?.length) {
console.log("Network requests:", data.data.network.length);
}
socket.disconnect();
}
});
```
***
### guardrail\_trigger
Agent needs human input to continue.
**Event:**
```json theme={null}
{
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "I need login credentials to proceed"
}
}
```
**Handler:**
```javascript theme={null}
socket.on("message", (data) => {
if (data.type === "guardrail_trigger") {
console.log("Guardrail:", data.data.value);
// Respond with required information
socket.emit("message", {
actionType: "guardrail",
prompt: "Username: demo@example.com, Password: demo123",
newState: "resume"
});
}
});
```
***
### error
Task failed with an error.
**Event:**
```json theme={null}
{
"type": "error",
"error": "Navigation timeout after 30 seconds",
"code": "NAVIGATION_TIMEOUT"
}
```
**Handler:**
```javascript theme={null}
socket.on("message", (data) => {
if (data.type === "error") {
console.error("Error:", data.error);
socket.disconnect();
}
});
```
***
### end\_session
Session terminated by server.
**Event:**
```json theme={null}
{
"type": "end_session",
"reason": "completed",
"message": "Session ended"
}
```
**Reasons:**
* `"completed"` - Task completed successfully
* `"terminated"` - User terminated session
* `"expired"` - Session expired (5 minutes of inactivity)
* `"terminateOnCompletion"` - Auto-terminated after task
* `"instance_lost"` - Instance connection permanently lost
**Handler:**
```javascript theme={null}
socket.on("end_session", (data) => {
console.log("Session ended:", data.reason);
socket.disconnect();
});
```
***
### instance:disconnected
Instance connection lost, entering grace period.
**Event:**
```json theme={null}
{
"type": "instance:disconnected",
"message": "Instance connection lost. Attempting reconnection...",
"gracePeriod": 300000
}
```
**Handler:**
```javascript theme={null}
socket.on("instance:disconnected", (data) => {
console.warn("Instance disconnected");
console.log("Grace period:", data.gracePeriod, "ms");
// Show "Reconnecting..." UI to user
});
```
***
### instance:reconnected
Instance connection restored.
**Event:**
```json theme={null}
{
"type": "instance:reconnected",
"message": "Instance connection restored"
}
```
**Handler:**
```javascript theme={null}
socket.on("instance:reconnected", (data) => {
console.log("Instance reconnected");
// Hide "Reconnecting..." UI
});
```
***
## Complete Working Example
```javascript theme={null}
import { io } from "socket.io-client";
async function runTaskWithWebSocket(prompt, apiKey) {
return new Promise(async (resolve, reject) => {
// Step 1: Create session
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({ task: { prompt } })
}).then(r => r.json());
console.log("Session created:", session.sessionId);
// Step 2: Connect to WebSocket
const socket = io("https://api.webrun.ai", {
auth: { sessionId: session.sessionId },
transports: ["websocket"]
});
// Step 3: Handle events
socket.on("connect", () => {
console.log("Connected");
});
socket.on("message", (data) => {
switch (data.type) {
case "agent":
console.log(data.content);
break;
case "action":
console.log(data.data.name);
break;
case "task_completed":
console.log("Done:", data.data.message);
console.log("Cost: $" + data.usage.cost);
socket.disconnect();
resolve(data);
break;
case "guardrail_trigger":
console.error("Guardrail:", data.data.value);
socket.disconnect();
reject(new Error(`Guardrail: ${data.data.value}`));
break;
case "error":
console.error("Error:", data.error);
socket.disconnect();
reject(new Error(data.error));
break;
}
});
socket.on("end_session", (data) => {
console.log("Session ended:", data.reason);
socket.disconnect();
});
socket.on("instance:disconnected", (data) => {
console.warn("Instance disconnected, reconnecting...");
});
socket.on("instance:reconnected", () => {
console.log("Instance reconnected");
});
socket.on("error", (err) => {
console.error("Socket error:", err);
reject(err);
});
socket.on("disconnect", () => {
console.log("Disconnected");
});
});
}
// Usage
try {
const result = await runTaskWithWebSocket(
"Go to google.com and search for Anthropic",
"wr_xxx"
);
console.log("Result:", result.data.message);
} catch (error) {
console.error("Task failed:", error.message);
}
```
***
## Reconnection Handling
### Automatic Reconnection
Socket.IO automatically reconnects on connection loss. The WebRun server maintains session state during brief disconnections.
```javascript theme={null}
const socket = io("https://api.webrun.ai", {
auth: { sessionId: session.sessionId },
transports: ["websocket"],
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: 5
});
socket.on("reconnect", (attemptNumber) => {
console.log(`Reconnected after ${attemptNumber} attempts`);
});
socket.on("reconnect_attempt", (attemptNumber) => {
console.log(`Reconnection attempt ${attemptNumber}...`);
});
socket.on("reconnect_error", (error) => {
console.error("Reconnection error:", error);
});
socket.on("reconnect_failed", () => {
console.error("Reconnection failed after all attempts");
// Session may be lost
});
```
***
### Instance Disconnection vs Socket Disconnection
Two types of disconnections:
**1. Socket Disconnection** (client-server connection)
* Handled automatically by Socket.IO
* Session state preserved
* Events resume after reconnection
**2. Instance Disconnection** (browser instance connection)
* Server loses connection to browser instance
* Grace period to recover
* You receive `instance:disconnected` event
* If recovered: `instance:reconnected` event
* If not recovered within grace period: session terminates
```javascript theme={null}
let instanceDisconnected = false;
socket.on("instance:disconnected", (data) => {
instanceDisconnected = true;
console.warn("Browser instance disconnected");
console.log(`Grace period: ${data.gracePeriod / 1000}s`);
// Show UI warning
showReconnectingUI();
});
socket.on("instance:reconnected", () => {
instanceDisconnected = false;
console.log("Browser instance restored");
// Hide UI warning
hideReconnectingUI();
});
socket.on("end_session", (data) => {
if (data.reason === "instance_lost") {
console.error("Instance could not be recovered");
// Notify user, restart task if needed
}
});
```
***
## Error Handling
### Error Handler
```javascript theme={null}
function setupErrorHandling(socket) {
// Socket.IO errors
socket.on("connect_error", (error) => {
console.error("Connection error:", error.message);
// Invalid sessionId, network issue, or server down
});
socket.on("error", (error) => {
console.error("Socket error:", error);
});
// Task errors
socket.on("message", (data) => {
if (data.type === "error") {
console.error("Task error:", data.error);
console.error("Code:", data.code);
// Handle specific error codes
switch (data.code) {
case "NAVIGATION_TIMEOUT":
console.log("Page took too long to load");
break;
case "ELEMENT_NOT_FOUND":
console.log("Agent couldn't find required element");
break;
case "SESSION_EXPIRED":
console.log("Session timed out");
break;
default:
console.log("Unknown error:", data.code);
}
socket.disconnect();
}
});
// Guardrail errors (unhandled)
socket.on("message", (data) => {
if (data.type === "guardrail_trigger") {
console.warn("Guardrail triggered but no handler provided");
console.warn("Agent says:", data.data.value);
// Optionally auto-stop
socket.emit("message", {
actionType: "guardrail",
prompt: "Cannot proceed",
newState: "stop"
});
}
});
}
```
***
## Sending Commands
You can send commands to control the session via WebSocket:
### Start New Task
```javascript theme={null}
socket.emit("message", {
actionType: "newTask",
newState: "start",
prompt: "Search for wireless keyboards",
maxDuration: 60000
});
```
### Pause Task
```javascript theme={null}
socket.emit("message", {
actionType: "state",
newState: "pause"
});
```
### Resume Task
```javascript theme={null}
socket.emit("message", {
actionType: "state",
newState: "resume"
});
```
### Stop Task
```javascript theme={null}
socket.emit("message", {
actionType: "state",
newState: "stop"
});
```
### Terminate Session
```javascript theme={null}
socket.emit("message", {
actionType: "state",
newState: "terminate"
});
```
### Respond to Guardrail
```javascript theme={null}
socket.emit("message", {
actionType: "guardrail",
prompt: "Username: user@example.com, Password: pass123",
newState: "resume"
});
```
### Manual Browser Control
```javascript theme={null}
// Take control
socket.emit("message", {
actionType: "interaction",
action: { type: "takeOverControl" }
});
// Click at coordinates
socket.emit("message", {
actionType: "interaction",
action: { type: "CLICK", x: 500, y: 300 }
});
// Type text
socket.emit("message", {
actionType: "interaction",
action: { type: "TYPE", text: "Hello world", humanLike: true }
});
// Press key
socket.emit("message", {
actionType: "interaction",
action: { type: "KEY_PRESS", key: "Enter" }
});
// Release control
socket.emit("message", {
actionType: "interaction",
action: { type: "releaseControl" }
});
```
***
## Advanced Pattern: Multi-Task with Live Updates
```javascript theme={null}
import { io } from "socket.io-client";
class WebRunWebSocketClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.socket = null;
this.sessionId = null;
}
async createSession(prompt) {
const response = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${this.apiKey}`
},
body: JSON.stringify({ task: { prompt } })
});
const session = await response.json();
this.sessionId = session.sessionId;
this.socket = io("https://api.webrun.ai", {
auth: { sessionId: this.sessionId },
transports: ["websocket"]
});
this.setupEventHandlers();
return session;
}
setupEventHandlers() {
this.socket.on("connect", () => {
console.log("Connected");
});
this.socket.on("message", (data) => {
this.handleEvent(data);
});
this.socket.on("end_session", (data) => {
console.log("Session ended:", data.reason);
this.disconnect();
});
this.socket.on("instance:disconnected", () => {
console.warn("Instance disconnected, reconnecting...");
});
this.socket.on("instance:reconnected", () => {
console.log("Instance reconnected");
});
}
handleEvent(data) {
switch (data.type) {
case "agent":
this.onAgent(data.content);
break;
case "action":
this.onAction(data.data);
break;
case "task_completed":
this.onTaskCompleted(data);
break;
case "guardrail_trigger":
this.onGuardrail(data.data);
break;
case "error":
this.onError(data);
break;
}
}
onAgent(content) {
console.log(content);
}
onAction(action) {
console.log(action.name);
}
onTaskCompleted(data) {
console.log(data.data.message);
console.log("Cost:", data.usage.cost);
}
onGuardrail(data) {
console.warn("Guardrail:", data.value);
// Override this method to handle guardrails
}
onError(data) {
console.error(data.error);
this.disconnect();
}
sendTask(prompt, terminateOnCompletion = false) {
return new Promise((resolve, reject) => {
this.socket.emit("message", {
actionType: "newTask",
newState: "start",
prompt,
terminateOnCompletion
});
const originalHandler = this.onTaskCompleted.bind(this);
this.onTaskCompleted = (data) => {
originalHandler(data);
resolve(data);
};
const originalErrorHandler = this.onError.bind(this);
this.onError = (data) => {
originalErrorHandler(data);
reject(new Error(data.error));
};
});
}
pause() {
this.socket.emit("message", {
actionType: "state",
newState: "pause"
});
}
resume() {
this.socket.emit("message", {
actionType: "state",
newState: "resume"
});
}
terminate() {
this.socket.emit("message", {
actionType: "state",
newState: "terminate"
});
}
disconnect() {
if (this.socket) {
this.socket.disconnect();
}
}
}
// Usage
const client = new WebRunWebSocketClient("wr_xxx");
await client.createSession("Go to amazon.com");
await client.sendTask("Search for wireless keyboards");
await client.sendTask("Add first result to cart", true); // terminates after
```
***
Simple polling-based integration
Respond to human-in-the-loop requests
# Common Issues & Solutions
Source: https://docs.webrun.ai/troubleshooting/common-issues
Troubleshooting guide for frequently encountered issues with WebRun
***
## Session Issues
### Session Stuck in Pending State
**Symptoms:**
* Session status remains `pending` indefinitely
* Session never transitions to `active` state
* No browser instance appears to be assigned
**Common Causes:**
* No available browser instances
* System experiencing high load
* Network connectivity issues
* Resource allocation bottleneck
**Solutions:**
1. **Wait and Check Status**
```javascript theme={null}
// Poll session status for up to 30 seconds
async function waitForSessionActive(sessionId, apiKey, maxWait = 30000) {
const startTime = Date.now();
while (Date.now() - startTime < maxWait) {
const response = await fetch(
`https://api.webrun.ai/start/session-status/${sessionId}`,
{
headers: { "Authorization": `Bearer ${apiKey}` }
}
);
const data = await response.json();
if (data.status === "active") {
return data;
}
if (data.status === "failed") {
throw new Error("Session failed to start");
}
await new Promise(r => setTimeout(r, 2000));
}
throw new Error("Session stuck in pending state");
}
```
2. **Terminate and Recreate**
```javascript theme={null}
// If session is stuck, terminate and create new one
await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
message: { actionType: "state", newState: "terminate" }
})
});
// Create new session
const newSession = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({ prompt })
});
```
3. **Check System Status**
* Visit [status.webrun.ai](https://status.webrun.ai)
* Look for ongoing incidents or maintenance
* Check response times and success rates
4. **Contact Support**
* If issue persists for > 2 minutes
* Provide session ID and timestamp
* Include error logs if available
**Prevention:**
* Implement timeout logic when creating sessions
* Use retry logic with exponential backoff
* Monitor system status before critical operations
***
### Tasks Timing Out
**Symptoms:**
* Tasks return `TASK_TIMEOUT` error
* Tasks exceed `maxDuration` limit
* Incomplete results with timeout message
**Common Causes:**
* Complex pages with heavy JavaScript
* Slow network connections
* Task requires multiple page loads
* Website has anti-bot protections
* Task instructions too complex
**Solutions:**
1. **Increase Maximum Duration**
```javascript theme={null}
const response = await fetch("https://api.webrun.ai/start/run-task", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
prompt: "Complex multi-step task",
maxDuration: 180000 // 3 minutes instead of default 60s
})
});
```
2. **Break Down Complex Tasks**
```javascript theme={null}
// Instead of one complex task:
// "Search for products, filter by price, add to cart, and checkout"
// Break into multiple simpler tasks:
const tasks = [
"Navigate to example.com and search for 'laptop'",
"Filter results by price range $500-$1000",
"Click on the first product",
"Add the product to cart"
];
for (const task of tasks) {
const result = await runTask(sessionId, task, apiKey);
console.log(`Completed: ${task}`);
}
```
3. **Use Starting URL**
```javascript theme={null}
// Skip navigation time by starting at target page
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
prompt: "Fill out the contact form",
startingUrl: "https://example.com/contact" // Skip homepage
})
});
```
4. **Optimize Task Instructions**
```javascript theme={null}
// Vague - may cause exploration and timeouts
prompt: "Find information about pricing"
// Specific - faster execution
prompt: "Click the 'Pricing' link in the navigation menu"
```
**Prevention:**
* Set realistic `maxDuration` based on task complexity
* Test tasks on fast network first
* Monitor task execution times
* Keep task instructions specific and focused
***
### Tasks Completing But No Result Returned
**Symptoms:**
* Polling returns `pending: true` indefinitely
* Task appears stuck even though browser finished
* No error message returned
**Common Causes:**
* Task is still genuinely running
* Network issue between browser instance and API
* Result notification was lost
* WebSocket connection dropped
**Solutions:**
1. **Continue Polling with Timeout**
```javascript theme={null}
async function pollWithTimeout(sessionId, taskId, apiKey, maxTime = 300000) {
const startTime = Date.now();
while (Date.now() - startTime < maxTime) {
const response = await fetch(
`https://api.webrun.ai/task/${sessionId}/${taskId}`,
{
headers: { "Authorization": `Bearer ${apiKey}` }
}
);
const data = await response.json();
if (!data.pending) {
return data;
}
// Wait before next poll
await new Promise(r => setTimeout(r, 2000));
}
throw new Error("Task polling timeout - no result received");
}
```
2. **Check WebSocket Events**
```javascript theme={null}
// If using WebSocket, monitor for task_completed event
const ws = new WebSocket(`wss://api.webrun.ai/ws?sessionId=${sessionId}`);
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === "task_completed") {
console.log("Task completed:", data);
}
};
```
3. **Terminate and Retry**
```javascript theme={null}
// If stuck for too long, terminate and retry
await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
message: { actionType: "state", newState: "stop" }
})
});
// Wait a moment then retry
await new Promise(r => setTimeout(r, 2000));
const retryResult = await runTask(sessionId, prompt, apiKey);
```
**Prevention:**
* Use WebSocket for real-time updates
* Implement polling with timeouts
* Monitor both polling and WebSocket channels
***
## Cost & Performance Issues
### High Token Usage / Unexpected Costs
**Symptoms:**
* Tasks consuming more tokens than expected
* Costs higher than estimated
* `usage` object shows large token counts
**Common Causes:**
* Complex pages with lots of DOM elements
* Multiple failed attempts and retries
* Long-running tasks with many interactions
* Not using token limits
* Navigation to unnecessary pages
**Solutions:**
1. **Set Token Limits**
```javascript theme={null}
const response = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
prompt: "Search for products",
maxInputTokens: 10000, // Limit context size
maxOutputTokens: 2000 // Limit response length
})
});
```
2. **Use Starting URL**
```javascript theme={null}
// Skip homepage navigation - saves tokens
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
prompt: "Fill search form",
startingUrl: "https://example.com/search" // Go directly to target
})
});
```
3. **Block Unnecessary Domains**
```javascript theme={null}
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
prompt: "Read article content"
})
});
```
4. **Simplify Task Instructions**
```javascript theme={null}
// Verbose - may cause exploration
prompt: "Navigate around the site and find pricing information, compare different plans, and tell me about the features"
// Concise - direct execution
prompt: "Click 'Pricing' in navigation and extract plan names and prices"
```
5. **Monitor Usage**
```javascript theme={null}
const result = await pollForResult(sessionId, taskId, apiKey);
console.log("Token Usage:", {
input: result.usage.inputTokens,
output: result.usage.outputTokens,
cost: result.usage.cost
});
// Track cumulative costs
totalCost += result.usage.cost;
```
**Prevention:**
* Always set `maxInputTokens` and `maxOutputTokens`
* Use `startingUrl` when possible
* Block ad networks and analytics domains
* Keep tasks focused and specific
* Test on simple pages first
***
## Guardrails & Interaction Issues
### Guardrails Triggering Unexpectedly
**Symptoms:**
* Agent frequently asks for input
* Tasks pause for user confirmation
* `guardrail_trigger` events fire often
**Common Causes:**
* Task instructions are ambiguous
* Website requires login/authentication
* CAPTCHA or security check encountered
* Agent uncertain about next action
* Multiple valid options available
**Solutions:**
1. **Make Instructions More Specific**
```javascript theme={null}
// Ambiguous - may trigger guardrail
prompt: "Buy something"
// Specific - clear action
prompt: "Add the first search result to cart, do not proceed to checkout"
```
2. **Provide Credentials Upfront**
```javascript theme={null}
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
prompt: "Login using username 'user@example.com' and password 'myPassword123', then navigate to dashboard"
})
});
```
3. **Handle Guardrails Programmatically**
```javascript theme={null}
async function handleGuardrails(sessionId, apiKey) {
const ws = new WebSocket(`wss://api.webrun.ai/ws?sessionId=${sessionId}`);
ws.onmessage = async (event) => {
const data = JSON.parse(event.data);
if (data.type === "guardrail_trigger") {
console.log("Guardrail:", data.data.value);
// Provide automated response
let response;
if (data.data.value.includes("login")) {
response = "Yes, use the credentials provided earlier";
} else if (data.data.value.includes("confirm")) {
response = "Yes, proceed";
} else {
// Get user input
response = await getUserInput(data.data.value);
}
// Resume with response
await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
message: {
actionType: "guardrail",
prompt: response,
newState: "resume"
}
})
});
}
};
}
```
4. **Avoid Sites Requiring Auth**
```javascript theme={null}
// Block login-required domains
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
prompt: "Research product information"
})
});
```
**Prevention:**
* Write clear, unambiguous task instructions
* Provide all necessary information upfront
* Test tasks on public pages first
* Handle common guardrail scenarios programmatically
***
## Streaming & Connection Issues
### Video Stream Not Loading
**Symptoms:**
* Streaming endpoint returns errors
* Video player shows no content
* Connection timeout on stream URL
**Common Causes:**
* Session not active yet
* Invalid session ID
* Network/firewall blocking WebRTC
* Browser instance crashed
**Solutions:**
1. **Verify Session is Active**
```javascript theme={null}
async function getStreamUrl(sessionId, apiKey) {
// Check session status first
const statusResponse = await fetch(
`https://api.webrun.ai/start/session-status/${sessionId}`,
{
headers: { "Authorization": `Bearer ${apiKey}` }
}
);
const status = await statusResponse.json();
if (status.status !== "active") {
throw new Error(`Session not ready: ${status.status}`);
}
// Get stream URL
return `https://api.webrun.ai/stream/${sessionId}`;
}
```
2. **Check Network Configuration**
```javascript theme={null}
// Ensure WebRTC ports are not blocked
// Required ports: TCP 443, UDP 49152-65535
// Test connection
const streamUrl = `https://api.webrun.ai/stream/${sessionId}`;
const testResponse = await fetch(streamUrl);
if (!testResponse.ok) {
console.error("Stream not accessible:", testResponse.status);
}
```
3. **Use Alternative Streaming Methods**
```javascript theme={null}
// If WebRTC fails, try SSE for updates
const eventSource = new EventSource(
`https://api.webrun.ai/stream/sse/${sessionId}?apiKey=${apiKey}`
);
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Stream update:", data);
};
```
**Related:**
* [Streaming Guide](/streaming)
* [Network Requirements](/getting-started/requirements)
***
### WebSocket Connection Issues
**Symptoms:**
* WebSocket fails to connect
* Connection drops frequently
* Events not received
**Common Causes:**
* Invalid API key or session ID
* Firewall blocking WebSocket connections
* Network instability
* Session expired
**Solutions:**
1. **Implement Reconnection Logic**
```javascript theme={null}
function connectWebSocket(sessionId, apiKey, maxRetries = 3) {
let retries = 0;
function connect() {
const ws = new WebSocket(
`wss://api.webrun.ai/ws?sessionId=${sessionId}&apiKey=${apiKey}`
);
ws.onopen = () => {
console.log("WebSocket connected");
retries = 0;
};
ws.onerror = (error) => {
console.error("WebSocket error:", error);
};
ws.onclose = (event) => {
console.log("WebSocket closed:", event.code);
// Attempt reconnection
if (retries < maxRetries) {
retries++;
const delay = Math.min(1000 * Math.pow(2, retries), 10000);
console.log(`Reconnecting in ${delay}ms...`);
setTimeout(connect, delay);
}
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
handleEvent(data);
};
return ws;
}
return connect();
}
```
2. **Fall Back to Polling**
```javascript theme={null}
let ws = null;
let pollingInterval = null;
try {
ws = connectWebSocket(sessionId, apiKey);
} catch (error) {
console.log("WebSocket failed, falling back to polling");
// Poll every 2 seconds
pollingInterval = setInterval(async () => {
const result = await fetch(
`https://api.webrun.ai/task/${sessionId}/${taskId}`,
{
headers: { "Authorization": `Bearer ${apiKey}` }
}
);
const data = await result.json();
if (!data.pending) {
clearInterval(pollingInterval);
handleResult(data);
}
}, 2000);
}
```
**Prevention:**
* Implement automatic reconnection
* Have polling fallback ready
* Monitor connection health
* Use heartbeat/ping messages
***
### Polling Not Working
**Symptoms:**
* Polling requests return 404
* Task ID not recognized
* No updates on task status
**Common Causes:**
* Incorrect task ID or session ID
* Task already completed and cleaned up
* Session expired
* Network request failing
**Solutions:**
1. **Verify IDs are Correct**
```javascript theme={null}
// Store task ID immediately after creation
const taskResponse = await fetch("https://api.webrun.ai/start/run-task", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
prompt: "Navigate to example.com"
})
});
const taskData = await taskResponse.json();
const taskId = taskData.taskId;
console.log("Created task:", taskId, "in session:", sessionId);
// Use exact IDs for polling
const result = await fetch(
`https://api.webrun.ai/task/${sessionId}/${taskId}`,
{
headers: { "Authorization": `Bearer ${apiKey}` }
}
);
```
2. **Handle Errors Gracefully**
```javascript theme={null}
async function pollTask(sessionId, taskId, apiKey) {
try {
const response = await fetch(
`https://api.webrun.ai/task/${sessionId}/${taskId}`,
{
headers: { "Authorization": `Bearer ${apiKey}` }
}
);
if (response.status === 404) {
throw new Error("Task or session not found - may have expired");
}
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || "Polling failed");
}
return await response.json();
} catch (error) {
console.error("Polling error:", error.message);
throw error;
}
}
```
3. **Check Session is Still Active**
```javascript theme={null}
// Before polling, verify session exists
const sessionStatus = await fetch(
`https://api.webrun.ai/start/session-status/${sessionId}`,
{
headers: { "Authorization": `Bearer ${apiKey}` }
}
);
const status = await sessionStatus.json();
if (status.error || status.status === "terminated") {
throw new Error("Session no longer active");
}
```
**Prevention:**
* Store IDs immediately when created
* Validate IDs before polling
* Check session status first
* Handle 404 errors gracefully
***
## CAPTCHA & Security Challenges
### CAPTCHA Blocking Tasks
**Symptoms:**
* Tasks fail at CAPTCHA pages
* Agent cannot proceed past security checks
* Guardrail triggers asking how to handle CAPTCHA
**Common Causes:**
* Website uses bot detection
* High security on target site
* Rate limiting triggered CAPTCHA
* IP address flagged
**Solutions:**
1. **Manual Intervention via Guardrails**
```javascript theme={null}
// When CAPTCHA is encountered, guardrail will trigger
ws.onmessage = async (event) => {
const data = JSON.parse(event.data);
if (data.type === "guardrail_trigger") {
if (data.data.value.includes("CAPTCHA") || data.data.value.includes("verification")) {
// Notify user to solve CAPTCHA
console.log("CAPTCHA detected - manual intervention required");
// User solves CAPTCHA in browser stream
const userConfirmation = await askUser("Have you solved the CAPTCHA?");
// Resume task
await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
message: {
actionType: "guardrail",
prompt: "CAPTCHA solved, continue",
newState: "resume"
}
})
});
}
}
};
```
2. **Use Manual Takeover**
```javascript theme={null}
// Switch to manual control for CAPTCHA
await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
message: { actionType: "state", newState: "manual" }
})
});
// User solves CAPTCHA via stream
// Return to agent control
await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
message: { actionType: "state", newState: "resume" }
})
});
```
3. **Avoid CAPTCHA-Heavy Sites**
```javascript theme={null}
// Add known CAPTCHA-heavy domains to avoid list
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
prompt: "Research products"
})
});
```
4. **Rate Limit Your Requests**
```javascript theme={null}
// Avoid triggering rate-limit CAPTCHAs
async function rateLimitedTasks(tasks, delayMs = 5000) {
const results = [];
for (const task of tasks) {
const result = await executeTask(task);
results.push(result);
// Wait between tasks
if (tasks.indexOf(task) < tasks.length - 1) {
await new Promise(r => setTimeout(r, delayMs));
}
}
return results;
}
```
**Prevention:**
* Use manual takeover mode when CAPTCHAs expected
* Rate limit requests to avoid triggering security
* Test target sites beforehand
* Have fallback strategy for CAPTCHA sites
***
## Debugging Tips
### Enable Verbose Logging
```javascript theme={null}
class WebRunClient {
constructor(apiKey, debug = false) {
this.apiKey = apiKey;
this.debug = debug;
}
async request(url, options) {
if (this.debug) {
console.log(`[DEBUG] Request to ${url}`);
console.log(`[DEBUG] Options:`, JSON.stringify(options, null, 2));
}
const response = await fetch(url, {
...options,
headers: {
...options.headers,
"Authorization": `Bearer ${this.apiKey}`
}
});
const data = await response.json();
if (this.debug) {
console.log(`[DEBUG] Response:`, JSON.stringify(data, null, 2));
}
return { response, data };
}
}
// Usage
const client = new WebRunClient(apiKey, true); // Enable debug mode
```
### Monitor All Events
```javascript theme={null}
function monitorAllEvents(sessionId, apiKey) {
const ws = new WebSocket(
`wss://api.webrun.ai/ws?sessionId=${sessionId}&apiKey=${apiKey}`
);
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(`[EVENT] ${data.type}:`, data);
// Log specific event types
switch (data.type) {
case "task_started":
console.log("Task started:", data.data.taskId);
break;
case "task_completed":
console.log("Task completed with usage:", data.data.usage);
break;
case "guardrail_trigger":
console.log("Guardrail triggered:", data.data.value);
break;
case "error":
console.error("Error occurred:", data.data);
break;
}
};
}
```
***
## Quick Reference
| Issue | First Thing to Try | Documentation |
| ------------------------ | -------------------------------------- | ---------------------------------------------------- |
| Session pending too long | Wait 30s, then terminate & recreate | [Sessions](/concepts/sessions) |
| Task timeout | Increase maxDuration or simplify task | [Tasks](/concepts/tasks) |
| High costs | Set maxInputTokens and maxOutputTokens | [Cost Optimization](/usage-guides/cost-optimization) |
| Guardrails firing | Make instructions more specific | [Guardrails](/usage-guides/guardrails) |
| Stream not loading | Verify session is active | [Streaming](/streaming) |
| WebSocket failing | Implement polling fallback | [Events](/events) |
| CAPTCHA blocking | Use manual takeover mode | [Manual Control](/control) |
***
## Next Steps
Complete list of error codes
Frequently asked questions
Guidelines for optimal usage
Contact our support team
# Error Codes Reference
Source: https://docs.webrun.ai/troubleshooting/errors-reference
Complete reference of all WebRun API error codes, status codes, and solutions
## Quick Fixes Summary
Jump to the solution for common errors:
| Error Code | Quick Fix | Details |
| ------------------------------------------------- | --------------------------------------------------- | ------------------------------ |
| [INVALID\_API\_KEY](#invalid_api_key) | Verify API key in Settings → API Keys | [Link](#invalid_api_key) |
| [SESSION\_NOT\_FOUND](#session_not_found) | Create new session with POST /start/start-session | [Link](#session_not_found) |
| [SESSION\_EXPIRED](#session_expired) | Sessions expire after maxDuration - create new one | [Link](#session_expired) |
| [SESSION\_LIMIT\_REACHED](#session_limit_reached) | Terminate unused sessions or upgrade plan | [Link](#session_limit_reached) |
| [TASK\_TIMEOUT](#task_timeout) | Increase maxDuration or simplify task | [Link](#task_timeout) |
| [TASK\_ALREADY\_RUNNING](#task_already_running) | Wait for completion or stop with newState: "stop" | [Link](#task_already_running) |
| [RATE\_LIMIT\_EXCEEDED](#rate_limit_exceeded) | Wait before retrying, implement exponential backoff | [Link](#rate_limit_exceeded) |
| [INSUFFICIENT\_BALANCE](#insufficient_balance) | Add credits at webrun.ai/billing | [Link](#insufficient_balance) |
| [NAVIGATION\_TIMEOUT](#navigation_timeout) | Retry request or check if website is accessible | [Link](#navigation_timeout) |
| [ELEMENT\_NOT\_FOUND](#element_not_found) | Rephrase task or wait for page load | [Link](#element_not_found) |
***
## Error Response Format
All errors follow a consistent structure:
```json theme={null}
{
"success": false,
"error": "Human-readable error message",
"code": "ERROR_CODE",
"details": { /* Additional context */ }
}
```
***
## HTTP Status Codes
| Status | Meaning | Common Causes |
| ------ | --------------------- | ---------------------------------- |
| `200` | Success | Request completed successfully |
| `400` | Bad Request | Invalid parameters, malformed JSON |
| `401` | Unauthorized | Missing or invalid API key |
| `402` | Payment Required | Insufficient account balance |
| `404` | Not Found | Session or task does not exist |
| `429` | Too Many Requests | Rate limit exceeded |
| `500` | Internal Server Error | Server-side issue |
| `503` | Service Unavailable | System maintenance or overload |
***
## Authentication Errors
### INVALID\_API\_KEY
```json theme={null}
{
"success": false,
"error": "Invalid API key",
"code": "INVALID_API_KEY"
}
```
**Solution:** Verify your API key is correct and active in Settings → API Keys.
**Related:**
* [Authentication Guide](/getting-started/authentication)
* [API Keys Management](https://app.webrun.ai)
***
### API\_KEY\_EXPIRED
```json theme={null}
{
"success": false,
"error": "API key has expired",
"code": "API_KEY_EXPIRED"
}
```
**Solution:** Generate a new API key in your account settings.
**Related:**
* [Regenerating API Keys](https://app.webrun.ai)
***
### UNAUTHORIZED
```json theme={null}
{
"success": false,
"error": "Authorization header missing",
"code": "UNAUTHORIZED"
}
```
**Solution:** Include `Authorization: Bearer YOUR_API_KEY` header in all requests.
**Example:**
```javascript theme={null}
const response = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${YOUR_API_KEY}`
},
body: JSON.stringify({ prompt: "Navigate to example.com" })
});
```
**Related:**
* [Authentication Guide](/getting-started/authentication)
***
## Session Errors
### SESSION\_NOT\_FOUND
```json theme={null}
{
"success": false,
"error": "Session a1b2c3d4e5f6 does not exist or has expired",
"code": "SESSION_NOT_FOUND"
}
```
**Causes:**
* Session was terminated
* Session expired (5 min of inactivity)
* Invalid sessionId
**Solution:** Create a new session with `POST /start/start-session`.
**Related:**
* [Session Lifecycle](/concepts/sessions)
* [Start Session API](/api-reference/sessions/start-session)
***
### SESSION\_EXPIRED
```json theme={null}
{
"success": false,
"error": "Session expired after 300 seconds of inactivity",
"code": "SESSION_EXPIRED"
}
```
**Solution:** Sessions expire after `maxDuration`. Create a new session for continuation.
**Best Practice:**
```javascript theme={null}
// Set appropriate maxDuration
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
prompt: "Your task",
maxDuration: 300000 // max task duration in milliseconds
})
});
```
**Related:**
* [Session Timeouts](/concepts/sessions#timeouts)
***
### SESSION\_LIMIT\_REACHED
```json theme={null}
{
"success": false,
"error": "Maximum concurrent sessions reached (limit: 5)",
"code": "SESSION_LIMIT_REACHED",
"details": {
"current": 5,
"limit": 5
}
}
```
**Solution:** Terminate unused sessions or upgrade your plan.
**Clean up sessions:**
```javascript theme={null}
// Terminate session when done
await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
message: { actionType: "state", newState: "terminate" }
})
});
```
**Related:**
* [Plan Limits](/pricing)
* [Session Management](/concepts/sessions)
***
### INSTANCE\_UNAVAILABLE
```json theme={null}
{
"success": false,
"error": "No browser instances available",
"code": "INSTANCE_UNAVAILABLE"
}
```
**Solution:** Wait and retry, or contact support if persistent.
**Retry with backoff:**
```javascript theme={null}
async function createSessionWithRetry(prompt, apiKey, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({ prompt })
});
const data = await response.json();
if (response.ok) return data;
if (data.code === "INSTANCE_UNAVAILABLE" && i < maxRetries - 1) {
await new Promise(r => setTimeout(r, 2000 * Math.pow(2, i)));
continue;
}
throw new Error(data.error);
} catch (error) {
if (i === maxRetries - 1) throw error;
}
}
}
```
***
## Task Execution Errors
### TASK\_NOT\_FOUND
```json theme={null}
{
"success": false,
"error": "Task x9y8z7w6v5u4 not found in session a1b2c3d4e5f6",
"code": "TASK_NOT_FOUND"
}
```
**Solution:** Verify taskId and sessionId are correct.
**Related:**
* [Task Polling](/api-reference/tasks/poll-task)
***
### TASK\_ALREADY\_RUNNING
```json theme={null}
{
"success": false,
"error": "A task is already running in this session",
"code": "TASK_ALREADY_RUNNING"
}
```
**Solution:** Wait for current task to complete or stop it with `newState: "stop"`.
**Stop running task:**
```javascript theme={null}
await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
message: { actionType: "state", newState: "stop" }
})
});
```
**Related:**
* [Task States](/concepts/tasks#states)
***
### TASK\_TIMEOUT
```json theme={null}
{
"success": false,
"error": "Task exceeded maximum duration of 60000ms",
"code": "TASK_TIMEOUT",
"usage": {
"inputTokens": 25000,
"outputTokens": 8000,
"cost": 0.0245
}
}
```
**Solution:** Increase `maxDuration` or simplify the task.
**Adjust timeouts:**
```javascript theme={null}
const response = await fetch("https://api.webrun.ai/start/run-task", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
prompt: "Complex task",
maxDuration: 120000 // 2 minutes
})
});
```
**Related:**
* [Task Configuration](/concepts/tasks#configuration)
* [Managing Costs](/troubleshooting/common-issues#high-costs)
***
### INVALID\_TASK\_DETAILS
```json theme={null}
{
"success": false,
"error": "prompt cannot be empty",
"code": "INVALID_TASK_DETAILS"
}
```
**Solution:** Provide a valid task description.
**Good task examples:**
```javascript theme={null}
// Good - specific and actionable
prompt: "Navigate to example.com and click the 'Sign Up' button"
// Good - clear objective
prompt: "Search for 'laptop' on amazon.com and get the price of the first result"
// Bad - too vague
prompt: "do something"
```
**Related:**
* [Writing Effective Tasks](/usage-guides/best-practices)
***
## Browser & Navigation Errors
### NAVIGATION\_TIMEOUT
```json theme={null}
{
"success": false,
"error": "Navigation timeout after 30 seconds",
"code": "NAVIGATION_TIMEOUT",
"details": {
"url": "https://example.com",
"timeout": 30000
}
}
```
**Causes:**
* Slow website
* Network issues
* Website blocking automated access
**Solution:**
* Retry the request
* Check if website is accessible
* Use `startingUrl` if navigating to a specific page
**Example:**
```javascript theme={null}
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
prompt: "Click the login button",
startingUrl: "https://example.com/login" // Start directly at destination
})
});
```
**Related:**
* [Navigation Options](/api-reference/sessions/start-session#parameters)
***
### PAGE\_CRASH
```json theme={null}
{
"success": false,
"error": "Browser page crashed during execution",
"code": "PAGE_CRASH"
}
```
**Solution:** Retry the task. If persistent, report to support with session details.
**Related:**
* [Getting Help](/troubleshooting/errors-reference#getting-help)
***
### ELEMENT\_NOT\_FOUND
```json theme={null}
{
"success": false,
"error": "Could not locate element matching criteria",
"code": "ELEMENT_NOT_FOUND"
}
```
**Causes:**
* Page structure changed
* Element inside iframe
* Element not yet loaded
**Solution:** Rephrase task description or wait for page load.
**Tips:**
```javascript theme={null}
// Instead of: "Click the button"
// Try: "Click the blue 'Submit' button at the bottom of the form"
// For dynamic content:
prompt: "Wait for the results to load, then click the first product"
```
**Related:**
* [Task Best Practices](/usage-guides/best-practices)
***
## Rate Limiting & Network Errors
### RATE\_LIMIT\_EXCEEDED
```json theme={null}
{
"success": false,
"message": "Rate limit exceeded. Please try again later."
}
```
**Solution:** Wait before retrying. Implement exponential backoff.
**Rate Limits by Endpoint:**
* `POST /start/start-session`: 10 requests/minute per user
* `POST /start/send-message`: 10 requests/minute per user
* `POST /start/run-task`: 10 requests/minute per user
* `GET /task/:sessionId/:taskId`: No rate limit
**Note:** Rate limits are per user (API key owner), not per API key.
**Exponential Backoff Implementation:**
```javascript theme={null}
async function makeRequestWithRetry(url, options, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch(url, options);
const data = await response.json();
if (response.ok) return data;
// Don't retry client errors (4xx) except rate limits
if (response.status >= 400 && response.status < 500 && response.status !== 429) {
throw new Error(`${data.code}: ${data.error}`);
}
// Retry on 5xx errors and rate limits
if (attempt < maxRetries - 1) {
const delay = Math.min(1000 * Math.pow(2, attempt), 10000);
console.log(`Retry ${attempt + 1}/${maxRetries} after ${delay}ms`);
await new Promise(r => setTimeout(r, delay));
continue;
}
throw new Error(`${data.code}: ${data.error}`);
} catch (error) {
if (attempt === maxRetries - 1) throw error;
}
}
}
```
**Related:**
* [API Limits](/api-reference/rate-limits)
***
## Billing & Payment Errors
### INSUFFICIENT\_BALANCE
```json theme={null}
{
"success": false,
"error": "Insufficient account balance ($0.50 remaining, $2.00 required)",
"code": "INSUFFICIENT_BALANCE",
"details": {
"balance": 0.50,
"required": 2.00
}
}
```
**Solution:** Add credits to your account at [webrun.ai/billing](https://webrun.ai/billing).
**Monitor balance:**
* Check your balance regularly in the dashboard
* Set up low balance alerts
* Consider auto-recharge options
**Related:**
* [Billing & Pricing](/pricing)
* [Usage Tracking](https://app.webrun.ai/usage)
***
### PAYMENT\_FAILED
```json theme={null}
{
"success": false,
"error": "Payment method declined",
"code": "PAYMENT_FAILED"
}
```
**Solution:** Update payment method in Settings → Billing.
**Common causes:**
* Expired card
* Insufficient funds
* Card issuer declined
* Invalid billing address
***
## Validation Errors
### INVALID\_PARAMETER
```json theme={null}
{
"success": false,
"error": "Invalid parameter 'maxDuration': must be at least 1000",
"code": "INVALID_PARAMETER",
"details": {
"parameter": "maxDuration",
"value": 500000,
"min": 1000
}
}
```
**Solution:** Check parameter requirements in API documentation.
**Parameter Ranges:**
* `maxDuration`: 1,000 - 300,000 ms (max task duration, default 5 minutes)
* `maxInputTokens`: 1,000 - 100,000 tokens
* `maxOutputTokens`: 100 - 50,000 tokens
**Related:**
* [API Reference](/api-reference/endpoints)
***
### MISSING\_REQUIRED\_FIELD
```json theme={null}
{
"success": false,
"error": "Missing required field: task.prompt",
"code": "MISSING_REQUIRED_FIELD",
"details": {
"field": "task.prompt"
}
}
```
**Solution:** Include all required fields in request body.
**Required fields by endpoint:**
**POST /start/start-session:**
* `prompt` (string)
**POST /start/send-message:**
* `sessionId` (string)
* `message` (object)
**POST /start/run-task:**
* `sessionId` (string)
* `prompt` (string)
**Related:**
* [API Reference](/api-reference/endpoints)
***
## MCP-Specific Errors
### MCP\_SESSION\_NOT\_FOUND
```json theme={null}
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32603,
"message": "Session not found"
}
}
```
**Solution:** Check your MCP session ID or reconnect to the SSE endpoint.
**Related:**
* [MCP Integration](/integrations/mcp)
***
### MCP\_METHOD\_NOT\_FOUND
```json theme={null}
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32601,
"message": "Method not found: invalid_method"
}
}
```
**Solution:** Use valid MCP methods (tools/list, tools/call, etc.).
**Valid MCP methods:**
* `tools/list`
* `tools/call`
* `resources/list`
* `resources/read`
**Related:**
* [MCP Methods](/integrations/mcp#methods)
***
### MCP\_INVALID\_REQUEST
```json theme={null}
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32600,
"message": "Invalid request"
}
}
```
**Solution:** Ensure request follows JSON-RPC 2.0 format with `jsonrpc: "2.0"`.
**Example:**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list",
"params": {}
}
```
**Related:**
* [MCP Protocol](/integrations/mcp#protocol)
***
## Error Handling Best Practices
### Complete Error Handling Example
```javascript theme={null}
async function executeTaskWithRetry(prompt, apiKey) {
let sessionId = null;
try {
// Create session with retry
const session = await makeRequestWithRetry(
"https://api.webrun.ai/start/start-session",
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({ prompt })
}
);
sessionId = session.sessionId;
// Execute task with guardrail handling
const result = await executeTaskWithGuardrails(
sessionId,
prompt,
apiKey
);
return result;
} catch (error) {
console.error("Task execution failed:", error.message);
// Clean up session on error
if (sessionId) {
await terminateSession(sessionId, apiKey);
}
throw error;
}
}
async function terminateSession(sessionId, apiKey) {
try {
await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
message: { actionType: "state", newState: "terminate" }
})
});
} catch (error) {
console.error("Failed to terminate session:", error.message);
}
}
```
### Handling Guardrails
```javascript theme={null}
async function executeTaskWithGuardrails(sessionId, prompt, apiKey) {
let attempts = 0;
const maxGuardrailAttempts = 3;
while (attempts < maxGuardrailAttempts) {
const result = await pollForResult(sessionId, taskId, apiKey);
if (result.type === "task_completed") {
return result;
}
if (result.type === "guardrail_trigger") {
console.log(`Guardrail triggered: ${result.data.value}`);
// Get user input
const userInput = await promptUser(result.data.value);
// Resume with input
await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
sessionId,
message: {
actionType: "guardrail",
prompt: userInput,
newState: "resume"
}
})
});
attempts++;
continue;
}
throw new Error("Unexpected result type");
}
throw new Error("Maximum guardrail attempts exceeded");
}
```
**Related:**
* [Guardrails Guide](/usage-guides/guardrails)
* [Error Handling Examples](/usage-guides/error-handling)
***
## Debugging Checklist
When encountering issues:
* [ ] Verify API key is valid and has correct permissions
* [ ] Check account balance is sufficient
* [ ] Confirm session/task IDs are correct
* [ ] Review task instructions for clarity
* [ ] Check network connectivity
* [ ] Look for error codes in responses
* [ ] Enable verbose logging
* [ ] Test with simpler task first
* [ ] Check system status page
* [ ] Review usage limits for your plan
***
## Getting Help
If you're still experiencing issues:
1. **Documentation:** Review relevant API docs
2. **Status Page:** Check [status.webrun.ai](https://status.webrun.ai)
3. **Support:** Email [support@webrun.ai](mailto:support@webrun.ai) with:
* Error code and full error response
* Session ID and task ID
* Task description
* Timestamp of occurrence
* Steps to reproduce
***
## Related Resources
Solutions for frequent problems
Answers to common questions
Guidelines for optimal usage
Complete endpoint documentation
# Frequently Asked Questions
Source: https://docs.webrun.ai/troubleshooting/faqs
Common questions about WebRun's browser automation platform
## Sessions & Performance
### How long can sessions run?
Sessions can run indefinitely while active and expire after 5 minutes of inactivity. The session inactivity timeout is fixed at 5 minutes and cannot be configured.
Tasks have a configurable `maxDuration` (in milliseconds) for maximum task execution time. Default and max is 300000 (5 minutes). Always terminate sessions when finished.
[Session lifecycle documentation](/concepts/sessions#lifecycle)
***
### Can I run parallel sessions?
Yes. Concurrent session limits:
* **Free Tier:** 2 sessions
* **Pro Tier:** 15 sessions
* **Enterprise:** Custom limits
When you hit the limit, new session requests fail with `SESSION_LIMIT_REACHED`. Terminate unused sessions before creating new ones or upgrade your plan.
[Session management](/concepts/sessions)
***
### What browsers does WebRun use?
Chrome only. Latest stable version. Standard desktop user agent (Windows 10, 64-bit).
We don't support Firefox, Safari, custom versions, or mobile emulation yet.
***
### What's the browser resolution?
1920×1080 (Full HD). Fixed resolution for all sessions.
Custom viewport sizes and mobile device emulation aren't supported yet.
***
## Authentication & Security
### How do I handle website login?
Four approaches:
**1. Secrets (recommended):**
Provide credentials upfront using the `secrets` parameter. The agent authenticates automatically without pausing. Secrets are matched by domain pattern and are never stored. They are discarded when the session ends.
```json theme={null}
{
"task": {
"prompt": "Log in and export the report",
"secrets": [
{ "match": "*.example.com", "fields": { "email": "user@example.com", "password": "pass123" } }
]
}
}
```
**2. Provide credentials in task description:**
```json theme={null}
{
"prompt": "Navigate to example.com/login, enter username 'user@example.com' and password 'pass123', then go to dashboard"
}
```
**3. Handle via guardrails:**
When the agent encounters a login form, it triggers a guardrail. Your app provides credentials through the guardrail response.
**4. Manual takeover:**
Use manual control to enter credentials yourself while watching the video stream.
[Secrets guide](/usage-guides/secrets) | [Guardrails guide](/usage-guides/handling-guardrails) | [Manual control](/usage-guides/manual-interaction)
***
### Is my data secure?
**Session isolation:** Each session runs in an isolated browser instance. No shared cookies, localStorage, or cache between sessions. Instances are destroyed after termination.
**Encryption:** All API communication uses HTTPS/TLS 1.3. WebSocket connections are encrypted (WSS).
**Data retention:** Session logs are deleted after 30 days. Screenshots and recordings are deleted with the session.
**Credentials:** WebRun doesn't store credentials you provide to websites. When using [secrets](/usage-guides/secrets), credentials are only attached to the active session and immediately discarded when the session is destroyed. They are never persisted to a database or disk. Don't hardcode credentials. Use environment variables.
***
### How do I handle CAPTCHAs?
CAPTCHAs require manual intervention. When the agent encounters a CAPTCHA, it triggers a guardrail. Use manual takeover to solve it while watching the video stream, then release control.
No automated CAPTCHA solving. Use rate limiting to reduce CAPTCHA frequency.
[Manual control guide](/usage-guides/manual-interaction)
***
## Integration & Compatibility
### Does WebRun work with my framework?
WebRun provides REST and WebSocket APIs. Any language or framework that makes HTTP requests works.
**Supported:**
* JavaScript/TypeScript (Node.js, Deno, Bun)
* Python (requests, httpx, FastAPI)
* Any language with HTTP/WebSocket support
**Popular integrations:**
* Next.js / React
* Express.js
* FastAPI / Django
* LangChain, LlamaIndex, Vercel AI SDK (via OpenAI-compatible endpoint)
[Integration guides](/integrations/rest-api)
***
### Can I use WebRun with MCP?
Yes. WebRun provides a native Model Context Protocol (MCP) server.
Install: `npx -y @webrun/mcp-server`
[MCP integration guide](/integrations/mcp-server)
***
### Can I use my own LLM API keys?
No. WebRun uses its own browser-optimized AI models. You cannot bring your own API keys or use different models.
Costs are included in your WebRun usage and billed based on input/output tokens.
[Pricing](/concepts/pricing)
***
## Pricing & Billing
### Is there a free tier?
Yes. \$5 free credits per month, 2 concurrent sessions, unlimited session duration (expires after 5 minutes of inactivity). All API features enabled.
Credits reset monthly and don't roll over.
[Pricing plans](/concepts/pricing)
***
### How are tokens counted?
**Input tokens:** Task description, page HTML/DOM content, previous conversation history, agent reasoning.
**Output tokens:** Agent actions, navigation decisions, extracted data, status messages.
Token costs:
* Input: \$0.60 per 1M tokens
* Output: \$1.80-2.70 per 1M tokens (model dependent)
Input tokens are cheaper because the model processes them in parallel. Output generation is sequential.
[Token usage guide](/concepts/pricing#token-pricing)
***
### Do idle sessions cost money?
No token costs during idle time. However, idle sessions occupy a concurrent session slot and consume compute time from creation until termination.
Always terminate sessions when finished to free up session slots.
[Cost optimization](/usage-guides/cost-optimization)
***
### Can I set spending limits?
Yes. Configure spending limits in your account at [app.webrun.ai/billing](https://app.webrun.ai/billing).
Options: Hard limits (API requests fail when reached) or soft limits (alerts only).
***
## Capabilities
### Can WebRun download and upload files?
Yes. WebRun can download files from websites and upload them to other platforms. This works for documents, reports, images, CSVs, and other common file types.
You can combine downloads and uploads in a single multi-task session to move files between systems, for example, exporting a report from one platform and uploading it to another.
**Example workflow:**
1. **Task 1:** "Download the monthly invoice from the billing dashboard"
2. **Task 2:** "Upload the invoice to the shared Google Drive folder"
[Supported interactions](/capabilities/supported-interactions) | [Multi-task workflows](/usage-guides/multi-task-workflows)
***
## Technical Details
### What User-Agent does WebRun use?
Standard Chrome User-Agent matching the latest stable version:
```
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36
```
Appears as Windows 10, 64-bit Chrome. Not marked as headless or automated.
Cannot currently customize user agent, platform, or browser version.
This is the User-Agent the *rendering browser* sends to sites for compatibility. Separately, WebRun's automated traffic is identifiable and verifiable at the network layer through the `WebRunAgent` bot identity - used to allow-list WebRun on Cloudflare-protected sites and other bot-management systems. See [Bot Identification](/concepts/bot-identification).
***
### Can I use proxies?
Yes. Proxy support is available on all plans. Two options:
* **WebRun-managed proxies**: specify a country and WebRun assigns a residential proxy (\$4/GB data transfer).
* **Custom proxies**: bring your own HTTP or SOCKS proxy server (no additional charge).
Proxies are applied at the device level with 2-3 seconds of cold-start latency, ensuring no IP leakage.
[Proxies guide](/usage-guides/proxies) | [API parameters](/api-reference/parameters#proxy)
***
### Can I access browser console logs?
Not directly. Critical JavaScript errors are captured and may be included in task results.
For debugging, use guardrails to ask the agent: "Tell me if there are any JavaScript errors visible on the page."
[Debugging guide](/troubleshooting/common-issues)
***
### Can WebRun access sites behind login?
Yes, with considerations:
**Works:** Username/password forms, cookie-based auth
**Limited:** 2FA/MFA (requires manual intervention), OAuth flows (complex), session persistence (cookies don't persist across different sessions)
Recommended approach: use [secrets](/usage-guides/secrets) to provide credentials upfront. Alternatively, provide credentials in the task description or handle via guardrails.
[Secrets guide](/usage-guides/secrets) | [Authentication patterns](/usage-guides/handling-guardrails)
***
## Support
### Where can I find code examples?
* [Quickstart guide](/getting-started/quickstart): Basic integration
* [API Reference](/api-reference/endpoints): All endpoints with examples
* [Usage guides](/usage-guides/multi-task-workflows): Common patterns
* [GitHub examples](https://github.com/webrun-ai/examples): Sample projects
***
### How do I get support?
**Free Tier:** Documentation, community Discord, email (48-hour response)
**Pro Tier:** Priority email (24-hour response), live chat during business hours
**Enterprise:** Dedicated account manager, 24/7 phone support, SLA guarantees
**Contact:** [support@webrun.ai](mailto:support@webrun.ai) | [discord.gg/webrun](https://discord.gg/webrun) | [status.webrun.ai](https://status.webrun.ai)
Before contacting support:
1. Check this documentation
2. Review [common issues](/troubleshooting/common-issues)
3. Check [error reference](/troubleshooting/errors-reference)
4. Check system status page
Include when reporting issues: Session ID, task ID, full error message, code snippet (redact API keys), timestamp.
***
## Related Resources
Complete error code documentation
Solutions for frequent problems
Get started in 5 minutes
Complete API documentation
# Controlling Sessions
Source: https://docs.webrun.ai/usage-guides/controlling-sessions
Control task execution with pause, resume, stop, and terminate commands
## Overview
Session control commands allow you to manage task execution dynamically. You can pause tasks for inspection, resume them, stop the current task, or terminate the entire session.
All control commands use the same endpoint but with different message payloads:
| Method | Endpoint | Best For |
| --------- | ------------------------------- | ------------------------------------------ |
| REST | `POST /start/send-message` | Stateless, serverless, simple integrations |
| WebSocket | `socket.emit("message", {...})` | Real-time events, live UIs |
***
## newTask
Start a new task in the current session. This is the only control action that returns a `taskId` for result tracking.
| Parameter | Type | Required | Description |
| ----------------------- | --------- | -------- | ------------------------------------------------------------------- |
| `actionType` | string | Yes | Must be `"newTask"` |
| `newState` | string | Yes | Must be `"start"` |
| `prompt` | string | Yes | Task description |
| `startingUrl` | string | No | URL to start from |
| `maxDuration` | number | No | Max time in ms (default: 300000) |
| `maxInputTokens` | number | No | Max input tokens (default: 100000) |
| `maxOutputTokens` | number | No | Max output tokens (default: 100000) |
| `terminateOnCompletion` | boolean | No | Auto-terminate after task (default: false) |
| `outputType` | string | No | Output format: `"text"`, `"structured_json"`, or `"structured_csv"` |
| `outputSchema` | object | No | JSON Schema for structured output |
| `files` | string\[] | No | File IDs to attach ([details](/environments/file-uploads)) |
Use REST for simple integrations, WebSocket for real-time event handling:
```bash REST theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "SESSION_ID",
"message": {
"actionType": "newTask",
"newState": "start",
"prompt": "Search for wireless keyboards",
"maxDuration": 60000,
"terminateOnCompletion": true
}
}'
```
```javascript WebSocket theme={null}
socket.emit("message", {
actionType: "newTask",
newState: "start",
prompt: "Search for wireless keyboards",
startingUrl: "https://amazon.com",
maxDuration: 60000,
maxInputTokens: 100000,
maxOutputTokens: 100000,
});
```
If the task completes within 50 seconds, you get the result inline:
```json theme={null}
{
"success": true,
"sessionId": "SESSION_ID",
"taskId": "TASK_ID",
"result": {
"type": "task_completed",
"data": {
"message": "Found 10 wireless keyboard results",
"prompt_tokens": 8500,
"completion_tokens": 2300,
"total_tokens": 10800
}
}
}
```
For longer tasks, you receive a `pollUrl` to check status. Poll every 2-3 seconds until complete:
```json theme={null}
{
"success": true,
"sessionId": "SESSION_ID",
"taskId": "TASK_ID",
"pending": true,
"pollUrl": "https://api.webrun.ai/task/SESSION_ID/TASK_ID",
"message": "Task still running. Poll GET /task/:sessionId/:taskId for result."
}
```
Set `terminateOnCompletion: true` on your final task to auto-close the session and avoid idle charges.
***
## pause
Pause the current task. The agent will stop after completing its current action and wait for a `resume` command.
**Use cases:**
* Inspect the current state before continuing
* Wait for external conditions to be met
* Synchronize with other systems
```bash REST theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "SESSION_ID",
"message": { "actionType": "state", "newState": "pause" }
}'
```
```javascript WebSocket theme={null}
socket.emit("message", { actionType: "state", newState: "pause" });
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Message sent successfully"
}
```
The agent will complete its current action before pausing. It does not immediately halt mid-action.
***
## resume
Resume a paused task. The agent will continue from where it left off.
```bash REST theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "SESSION_ID",
"message": { "actionType": "state", "newState": "resume" }
}'
```
```javascript WebSocket theme={null}
socket.emit("message", { actionType: "state", newState: "resume" });
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Message sent successfully"
}
```
***
## stop
Stop the current task immediately. The session remains active and ready for new tasks.
**Difference from terminate:**
* `stop`: Ends the current task only, session stays active
* `terminate`: Ends the entire session and all connections
```bash REST theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "SESSION_ID",
"message": { "actionType": "state", "newState": "stop" }
}'
```
```javascript WebSocket theme={null}
socket.emit("message", { actionType: "state", newState: "stop" });
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Message sent successfully"
}
```
**When to use:**
* Task is taking too long
* Task is heading in wrong direction
* Need to intervene and start a different task
**After stopping:**
You can immediately send a new task or manually interact with the browser before sending the next task.
***
## terminate
End the session completely. This closes the browser instance and all connections (WebSocket, video stream).
```bash REST theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "SESSION_ID",
"message": { "actionType": "state", "newState": "terminate" }
}'
```
```javascript WebSocket theme={null}
socket.emit("message", { actionType: "state", newState: "terminate" });
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Message sent successfully"
}
```
Always terminate sessions when you're done to avoid unnecessary charges. Idle sessions expire after 5 minutes of inactivity, but you should terminate explicitly to avoid unnecessary costs.
***
## State Transitions
Understanding how session states work:
```
┌─────────┐ ┌──────────┐ ┌─────────────┐
│ Pending │────►│ Active │────►│ Completed │
└─────────┘ └──────────┘ └─────────────┘
│
├───────────► Paused ──────► Active (resume)
│
├───────────► Stopped ─────► Active (new task)
│
└───────────► Terminated
```
| State | Description | Can Transition To |
| ------------ | -------------------------------- | ---------------------------------------------- |
| `pending` | Session initializing | `active` |
| `active` | Task running | `paused`, `completed`, `stopped`, `terminated` |
| `paused` | Task paused, waiting for resume | `active`, `stopped`, `terminated` |
| `stopped` | Task stopped, ready for new task | `active`, `terminated` |
| `completed` | Task finished successfully | `active` (new task), `terminated` |
| `terminated` | Session ended | None (final state) |
***
## Cost Optimization Tips
### 1. Terminate Sessions Promptly
Don't leave sessions idle. Terminate them as soon as your workflow completes:
```javascript theme={null}
// Option A: Explicit terminate
await fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId: session.sessionId,
message: { actionType: "state", newState: "terminate" }
})
});
// Option B: Auto-terminate on last task
await fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId: session.sessionId,
message: {
actionType: "newTask",
newState: "start",
prompt: "Final task",
terminateOnCompletion: true // ← Session closes after this task
}
})
});
```
### 2. Use `stop` to Intervene Early
If a task is taking too long or going off-track, stop it immediately:
```javascript theme={null}
// Monitor task progress
const taskStatus = await fetch(`${BASE}/task/${sessionId}/${taskId}`)
.then(r => r.json());
if (taskStatus.usage.cost > 0.10) {
// Stop task if cost exceeds threshold
await fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId: sessionId,
message: { actionType: "state", newState: "stop" }
})
});
}
```
### 3. Set Appropriate `maxDuration`
Limit task duration to prevent runaway costs:
```javascript theme={null}
socket.emit("message", {
actionType: "newTask",
newState: "start",
prompt: "Search for products",
maxDuration: 30000 // 30 seconds max
});
```
### 4. Use `pause` for Inspection
Pause tasks to inspect state before continuing:
```javascript theme={null}
// Pause to check if we're on the right track
await sendMessage({ actionType: "state", newState: "pause" });
// Check video stream or poll for current state
const canContinue = await checkIfTaskOnTrack();
if (canContinue) {
await sendMessage({ actionType: "state", newState: "resume" });
} else {
await sendMessage({ actionType: "state", newState: "stop" });
// Start a different task
}
```
***
## Control Flow Example
Complete example showing pause/resume/stop/terminate in action:
```javascript theme={null}
const API_KEY = "YOUR_API_KEY";
const BASE = "https://api.webrun.ai";
async function controlFlowDemo() {
// Create session
const session = await fetch(`${BASE}/start/start-session`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
mode: "default",
task: {
prompt: "Go to amazon.com",
startingUrl: "https://amazon.com"
}
})
}).then(r => r.json());
const sessionId = session.sessionId;
// Start a task
const task = await sendMessage(sessionId, {
actionType: "newTask",
newState: "start",
prompt: "Search for 'mechanical keyboard'"
});
// Wait a bit, then pause to inspect
await new Promise(r => setTimeout(r, 5000));
await sendMessage(sessionId, { actionType: "state", newState: "pause" });
console.log("Task paused for inspection");
// Check something (e.g., video stream, task status)
await new Promise(r => setTimeout(r, 3000));
// Decision point
const shouldContinue = true; // Your logic here
if (shouldContinue) {
// Resume the task
await sendMessage(sessionId, { actionType: "state", newState: "resume" });
console.log("Task resumed");
// Wait for completion
await pollForResult(sessionId, task.taskId);
} else {
// Stop and try something different
await sendMessage(sessionId, { actionType: "state", newState: "stop" });
console.log("Task stopped");
// Start different task
await sendMessage(sessionId, {
actionType: "newTask",
newState: "start",
prompt: "Navigate to homepage instead"
});
}
// Terminate when done
await sendMessage(sessionId, { actionType: "state", newState: "terminate" });
console.log("Session terminated");
}
async function sendMessage(sessionId, message) {
return fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({ sessionId, message })
}).then(r => r.json());
}
async function pollForResult(sessionId, taskId) {
const maxAttempts = 60;
const interval = 2000;
for (let i = 0; i < maxAttempts; i++) {
const res = await fetch(`${BASE}/task/${sessionId}/${taskId}`, {
headers: { "Authorization": `Bearer ${API_KEY}` }
});
const data = await res.json();
if (data.type === "task_completed") return data;
if (data.type === "guardrail_trigger") throw new Error(`Guardrail: ${data.data.value}`);
if (data.status === "failed") throw new Error(data.error);
if (data.pending) {
await new Promise(r => setTimeout(r, interval));
continue;
}
return data;
}
throw new Error("Polling timeout");
}
controlFlowDemo();
```
***
Take over control and interact manually
Respond to agent requests for input
Upload files for the agent to use in sessions
# Cost Optimization
Source: https://docs.webrun.ai/usage-guides/cost-optimization
Reduce costs while maintaining performance
WebRun charges for session time and token usage. Three quick changes can cut your costs by 50% or more.
## Quick Wins
### 1. Terminate Sessions Explicitly
Set `terminateOnCompletion: true` on your final task, or call terminate explicitly. This alone reduces costs by 50% if you're currently letting sessions timeout.
```javascript theme={null}
// Single task - auto-terminates
const result = await fetch("https://api.webrun.ai/start/run-task", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
task: {
prompt: "Extract data from this page"
}
})
});
// Multi-task - terminate on last task
const finalTask = await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId,
message: {
actionType: "newTask",
prompt: "Final task here",
terminateOnCompletion: true
}
}
});
```
***
### 2. Write Concise Task Descriptions
Shorter descriptions = fewer input tokens. Be specific, not verbose.
**Verbose (150 tokens):**
```
"Please navigate to the Amazon website and then perform a search for wireless keyboards. After you get the results, I need you to look through them carefully and find the ones that have good ratings, preferably above 4 stars, and then return me a list of the top 5 products with their titles, prices, and rating information."
```
**Concise (35 tokens):**
```
"Go to Amazon, search 'wireless keyboard'. Return top 5 with rating ≥ 4.0 as JSON: title, price, rating."
```
**Impact:** 75% reduction in input tokens for this task.
***
### 3. Set `startingUrl` When Known
Skip navigation by providing the starting URL directly.
```javascript theme={null}
{
"mode": "default",
"task": {
"prompt": "Search for products",
"startingUrl": "https://amazon.com" // Skips "go to amazon.com" step
}
}
```
**Impact:** Saves 5-10 seconds and \~500-1000 tokens per task.
***
## Additional Optimizations
### Set Appropriate `maxDuration`
Limit task duration to prevent runaway costs:
```javascript theme={null}
{
"task": {
"prompt": "Quick search task",
"maxDuration": 30000 // 30 seconds max task duration
}
}
```
**Guidelines:**
* Simple searches: 30,000ms (30s)
* Form filling: 60,000ms (1 min)
* Multi-step workflows: 120,000ms (2 min)
***
### Batch Related Tasks in Single Sessions
Reuse sessions for related tasks instead of creating new ones.
**Expensive:**
```javascript theme={null}
await runTask("Go to amazon.com"); // New session
await runTask("Search for keyboards"); // Another new session
await runTask("Get first result"); // Yet another session
```
**Optimized:**
```javascript theme={null}
const session = await startSession("Go to amazon.com");
await sendTask(session, "Search for keyboards");
await sendTask(session, "Get first result", { terminateOnCompletion: true });
```
**Impact:** 3x reduction in session overhead costs.
***
### Limit Token Usage
For simple tasks, reduce token limits:
```javascript theme={null}
{
"task": {
"prompt": "Get product price",
"maxInputTokens": 10000, // Lower for simple tasks (default: 100000)
"maxOutputTokens": 1000 // Lower for short responses (default: 100000)
}
}
```
***
### Use Policies to Prevent Detours
Use [automation policies](/concepts/policies) with domain rules to block unnecessary domains and prevent wasted navigation.
***
### Use Custom Proxies for High-Bandwidth Tasks
WebRun-managed proxies cost **\$2 per GB** of data transfer. For tasks that download large files or scrape image-heavy pages, use your own proxy to avoid per-GB charges. Only enable proxies when you actually need geographic targeting or IP management. Each proxied session adds 2-3 seconds of cold-start latency.
```javascript theme={null}
{
"proxy": {
"source": "custom",
"type": "http",
"host": "your-proxy.com",
"port": "8080"
},
"task": {
"prompt": "Download all product images from the catalog"
}
}
```
See the [Proxies guide](/usage-guides/proxies) for configuration details.
***
## Monitoring Costs
**Real-time:** Check `usage.cost` in every API response.
```json theme={null}
{
"success": true,
"sessionId": "abc123",
"taskId": "xyz789",
"type": "task_completed",
"data": {
"message": "Task completed successfully"
},
"usage": {
"prompt_tokens": 12450,
"completion_tokens": 3200,
"total_tokens": 15650,
"completion_time": 23.5,
"cost": 0.0124
}
}
```
**Dashboard:** View historical usage at [app.webrun.ai/usage](https://app.webrun.ai/usage).
**During polling:** The `usage` object updates in real-time as tasks execute.
***
## Cost Optimization Checklist
* [ ] Use `/start/run-task` for single tasks (auto-terminates)
* [ ] Set `terminateOnCompletion: true` on final tasks in multi-task workflows
* [ ] Write concise, specific task descriptions
* [ ] Provide `startingUrl` when the starting point is known
* [ ] Set appropriate `maxDuration` based on task complexity
* [ ] Batch related tasks into single sessions
* [ ] Limit `maxInputTokens` and `maxOutputTokens` for simple tasks
* [ ] Use [policies](/concepts/policies) to prevent accidental navigation
* [ ] Use custom proxies instead of WebRun-managed for high-bandwidth tasks
* [ ] Monitor `usage.cost` in responses to track spending
***
## Example: Before & After
**Before: Expensive**
```javascript theme={null}
// Creates 3 separate sessions
const result1 = await runTask("Go to amazon.com");
await sleep(5000); // Forgot to terminate, paying for idle time
const result2 = await runTask("Please navigate to the search box and then type in 'wireless keyboard' and press enter");
await sleep(5000);
const result3 = await runTask("Get me information about the first result");
```
**After: Optimized**
```javascript theme={null}
// Single session, concise tasks, explicit termination
const session = await startSession({
mode: "default",
task: {
prompt: "Go to amazon.com",
startingUrl: "https://amazon.com",
maxDuration: 60000 // 1 minute max
}
});
await sendTask(session, "Search 'wireless keyboard'");
await sendTask(session, "Return first result as JSON: title, price, rating", {
terminateOnCompletion: true
});
```
**Savings:** \~70% cost reduction from session reuse, concise prompts, and explicit termination.
***
Understand WebRun's pricing model
Manage session lifecycle
Chain tasks efficiently
Request minimal, structured responses
# Handling Guardrails
Source: https://docs.webrun.ai/usage-guides/handling-guardrails
Detect and respond to guardrails when the AI agent needs human input or guidance
## Overview
Guardrails are safety mechanisms that pause agent execution when:
* The agent needs sensitive information (credentials, payment details)
* The agent is uncertain and requires human guidance
* The agent encounters content that requires human verification
* The agent detects potential [policy](/concepts/policies) violations
When a guardrail triggers, the task pauses and waits for your response before continuing.
**Prefer secrets for login credentials.** If you know which sites the agent will authenticate with, use the [`secrets` parameter](/usage-guides/secrets) to provide credentials upfront. This avoids guardrail interruptions entirely, so the task runs without pausing. Secrets are never stored. They are discarded when the session ends.
***
## Detecting Guardrails
Guardrails are detected differently depending on your integration method.
### REST API (Polling)
When polling a task endpoint, a guardrail appears as:
```bash theme={null}
curl https://api.webrun.ai/task/SESSION_ID/TASK_ID \
-H "Authorization: Bearer YOUR_API_KEY"
```
**Response:**
```json theme={null}
{
"success": true,
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "I need login credentials to proceed"
}
}
```
### WebSocket (Real-Time)
With WebSocket connections, you receive immediate notifications:
```javascript theme={null}
socket.on("message", (data) => {
if (data.type === "guardrail_trigger") {
console.log("Guardrail triggered:", data.data.type);
console.log("Agent says:", data.data.value);
// Handle guardrail response
handleGuardrail(data.data);
}
});
```
**Example guardrail event:**
```json theme={null}
{
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "I need the login credentials to continue"
}
}
```
***
## Responding to Guardrails
Once a guardrail triggers, respond with the requested information or guidance. The `newState: "resume"` parameter tells the agent to **continue execution from the exact point where the guardrail paused**. It doesn't restart the task.
```bash REST theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "SESSION_ID",
"message": {
"actionType": "guardrail",
"prompt": "Username: demo@example.com, Password: demo123",
"newState": "resume"
}
}'
```
```javascript WebSocket theme={null}
socket.on("message", (data) => {
if (data.type === "guardrail_trigger") {
console.log("Agent needs:", data.data.value);
socket.emit("message", {
actionType: "guardrail",
prompt: "Username: demo@example.com, Password: demo123",
newState: "resume"
});
}
});
```
| Parameter | Type | Required | Description |
| ------------ | ------ | -------- | ------------------------------------------ |
| `actionType` | string | Yes | Must be `"guardrail"` |
| `prompt` | string | Yes | Your response to the agent |
| `newState` | string | Yes | `"resume"` to continue, `"stop"` to cancel |
**Response:**
```json theme={null}
{
"success": true,
"message": "Message sent successfully"
}
```
***
## Routing Guardrails to a Chat User
Polling and WebSocket both assume something on your side is watching the session when a guardrail triggers. For unattended workloads (scheduled triggers, long-running CI jobs, MCP tasks kicked off from another tool) that isn't always the case. As a fallback, a guardrail can be delivered to a chat user connected to the session's [environment](/environments/overview), and their reply is forwarded back to the session.
### How it works
When a session raises a guardrail, the platform first checks whether you're actively handling it (polling responses or a live WebSocket subscription on the session). If you are, the prompt reaches you the usual way and nothing else happens.
If no one is actively watching, the platform looks for a chat user (Telegram, WhatsApp, Slack, Discord, or Teams) connected to the same environment. If one is available, the guardrail prompt is sent to them in chat. Their reply is forwarded to the session exactly like a regular guardrail response: `resume` to continue or `stop` to cancel.
Whoever answers first wins. If your API caller and a chat user both respond at the same time, only the first reply reaches the session.
### Choosing a reach-out mode
Chat reach-out is controlled per session by the `reachOutMode` parameter. It takes one of three values, and defaults to `"guardrail_only"`:
| Value | Behavior |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| `"off"` | No proactive chat messages. Guardrails and results stay on the API/WebSocket channel only. |
| `"guardrail_only"` | Default. The bot pings the chat user only when the session hits a guardrail (CAPTCHA, 2FA, verification, login, etc.). |
| `"full"` | The bot pings on guardrails **and** also delivers the task result to chat when the task completes. |
To turn chat routing off for a specific session, pass `"reachOutMode": "off"` at session creation:
```json /start/start-session theme={null}
{
"environmentId": "683a1f2e4b0c1d2e3f4a5b6c",
"reachOutMode": "off",
"mode": "default",
"task": {
"prompt": "Export the monthly financial report and download the PDF"
}
}
```
```json /start/run-task theme={null}
{
"reachOutMode": "off",
"environmentId": "683a1f2e4b0c1d2e3f4a5b6c",
"task": {
"prompt": "Export the monthly financial report and download the PDF"
}
}
```
`reachOutMode` is set at session creation and applies for the lifetime of the session. There is no way to change it later. Start a new session if you need different behavior.
### When to set `reachOutMode` to `"off"`
* **Sensitive sessions.** Anything involving private credentials, financial data, or personal information you don't want surfaced through chat.
* **Shared environments.** When multiple people use the same environment but only your code should handle guardrails for this session.
* **Deterministic flows.** Automations that must respond programmatically. Turning chat routing off ensures the prompt always waits for your API call instead of being answered by someone else first.
### When to use `"full"`
Use `"full"` for unattended automations where a human on chat should also receive the task result, for example, a scheduled run kicked off via MCP or REST with no live client polling. When the session completes, the chat user is sent the task result in addition to (not instead of) the normal API/webhook delivery. The chat fan-out only fires when the caller is offline (no live WebSocket subscriber on the session).
If you'd rather avoid guardrails entirely for known auth flows, provide credentials upfront with [secrets](/usage-guides/secrets) instead. Secrets are never stored and are scoped to the session.
***
## Common Guardrail Scenarios
### 1. Login Credentials
**Guardrail:**
```json theme={null}
{
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "I need login credentials for this site"
}
}
```
**Response:**
```javascript theme={null}
socket.emit("message", {
actionType: "guardrail",
prompt: "Use username: user@example.com and password: mypassword123",
newState: "resume"
});
```
**Alternative (manual input):**
```javascript theme={null}
// Take control and enter credentials manually
socket.emit("message", {
actionType: "interaction",
action: { type: "takeOverControl" }
});
// Enter credentials via manual interaction
socket.emit("message", {
actionType: "interaction",
action: { type: "CLICK", x: 400, y: 300 }
});
socket.emit("message", {
actionType: "interaction",
action: { type: "TYPE", text: "user@example.com", humanLike: true }
});
// Release control
socket.emit("message", {
actionType: "interaction",
action: { type: "releaseControl" }
});
// Resume task
socket.emit("message", {
actionType: "guardrail",
prompt: "Credentials entered, please continue",
newState: "resume"
});
```
***
### 2. Payment Information
**Guardrail:**
```json theme={null}
{
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "Payment information required to complete checkout"
}
}
```
**Response (provide details):**
```javascript theme={null}
socket.emit("message", {
actionType: "guardrail",
prompt: "Card number: 4111111111111111, Expiry: 12/25, CVV: 123",
newState: "resume"
});
```
**Response (cancel):**
```javascript theme={null}
socket.emit("message", {
actionType: "guardrail",
prompt: "Do not proceed with payment",
newState: "stop"
});
```
***
### 3. Ambiguous Instructions
**Guardrail:**
```json theme={null}
{
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "I found 5 products matching 'wireless keyboard'. Which one should I select?"
}
}
```
**Response:**
```javascript theme={null}
socket.emit("message", {
actionType: "guardrail",
prompt: "Select the first one with the highest rating",
newState: "resume"
});
```
***
### 4. Verification Needed
**Guardrail:**
```json theme={null}
{
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "This action requires two-factor authentication code"
}
}
```
**Response:**
```javascript theme={null}
// Get 2FA code from your system
const twoFactorCode = await getTwoFactorCode();
socket.emit("message", {
actionType: "guardrail",
prompt: `2FA code: ${twoFactorCode}`,
newState: "resume"
});
```
***
### 5. CAPTCHA Detection
**Guardrail:**
```json theme={null}
{
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "CAPTCHA detected, manual solving required"
}
}
```
**Response (manual solving):**
```javascript theme={null}
// Take control for manual CAPTCHA solving
socket.emit("message", {
actionType: "interaction",
action: { type: "takeOverControl" }
});
// User solves CAPTCHA via video stream...
// Once solved:
socket.emit("message", {
actionType: "interaction",
action: { type: "releaseControl" }
});
socket.emit("message", {
actionType: "guardrail",
prompt: "CAPTCHA solved, continue",
newState: "resume"
});
```
***
### 6. Content Verification
**Guardrail:**
```json theme={null}
{
"type": "guardrail_trigger",
"data": {
"type": "human_input_needed",
"value": "I found content that may be sensitive. Please verify before proceeding."
}
}
```
**Response (approve):**
```javascript theme={null}
socket.emit("message", {
actionType: "guardrail",
prompt: "Content verified, safe to proceed",
newState: "resume"
});
```
**Response (reject):**
```javascript theme={null}
socket.emit("message", {
actionType: "guardrail",
prompt: "Do not proceed with this content",
newState: "stop"
});
```
***
## Automated Guardrail Handling
For predictable guardrails (like login credentials), implement automated handling:
### Pattern 1: Credential Manager
```javascript theme={null}
class GuardrailHandler {
constructor(credentials) {
this.credentials = credentials;
}
handle(guardrailData) {
const message = guardrailData.value.toLowerCase();
// Detect login request
if (message.includes("login") || message.includes("credentials")) {
return {
actionType: "guardrail",
prompt: `Username: ${this.credentials.username}, Password: ${this.credentials.password}`,
newState: "resume"
};
}
// Detect 2FA request
if (message.includes("2fa") || message.includes("two-factor")) {
const code = this.getTwoFactorCode();
return {
actionType: "guardrail",
prompt: `2FA code: ${code}`,
newState: "resume"
};
}
// Detect payment request
if (message.includes("payment") || message.includes("credit card")) {
return {
actionType: "guardrail",
prompt: "Do not proceed with payment",
newState: "stop"
};
}
// Default: require human intervention
return null;
}
getTwoFactorCode() {
// Integrate with your 2FA system
return "123456";
}
}
// Usage
const handler = new GuardrailHandler({
username: "user@example.com",
password: "securepassword123"
});
socket.on("message", (data) => {
if (data.type === "guardrail_trigger") {
const response = handler.handle(data.data);
if (response) {
// Automated response
socket.emit("message", response);
} else {
// Escalate to human
console.log("Human intervention required:", data.data.value);
notifyHuman(data.data);
}
}
});
```
***
### Pattern 2: Rule-Based Handler
```javascript theme={null}
const guardrailRules = [
{
pattern: /login|credentials|username|password/i,
response: (data) => ({
actionType: "guardrail",
prompt: process.env.LOGIN_CREDENTIALS,
newState: "resume"
})
},
{
pattern: /captcha/i,
response: (data) => {
// Trigger manual intervention
return "MANUAL";
}
},
{
pattern: /payment|credit card|billing/i,
response: (data) => ({
actionType: "guardrail",
prompt: "Skip payment step",
newState: "stop"
})
},
{
pattern: /which.*select|choose.*option/i,
response: (data) => ({
actionType: "guardrail",
prompt: "Select the first option",
newState: "resume"
})
}
];
function handleGuardrailWithRules(guardrailData) {
const message = guardrailData.value;
for (const rule of guardrailRules) {
if (rule.pattern.test(message)) {
const response = rule.response(guardrailData);
if (response === "MANUAL") {
console.log("Manual intervention required");
return null;
}
return response;
}
}
// No rule matched, require human
return null;
}
// Usage
socket.on("message", (data) => {
if (data.type === "guardrail_trigger") {
const response = handleGuardrailWithRules(data.data);
if (response) {
socket.emit("message", response);
} else {
// Escalate to human
alertHuman(data.data);
}
}
});
```
***
### Pattern 3: Async Handler with Timeout
```javascript theme={null}
class AsyncGuardrailHandler {
constructor(timeout = 30000) {
this.timeout = timeout;
this.pendingGuardrails = new Map();
}
async handle(sessionId, guardrailData) {
// Try automated handling first
const autoResponse = this.tryAutomatic(guardrailData);
if (autoResponse) {
return autoResponse;
}
// Fall back to human with timeout
return this.requestHumanInput(sessionId, guardrailData);
}
tryAutomatic(guardrailData) {
const message = guardrailData.value.toLowerCase();
if (message.includes("login")) {
return {
actionType: "guardrail",
prompt: `Username: ${process.env.USERNAME}, Password: ${process.env.PASSWORD}`,
newState: "resume"
};
}
return null;
}
async requestHumanInput(sessionId, guardrailData) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
this.pendingGuardrails.delete(sessionId);
reject(new Error("Guardrail response timeout"));
}, this.timeout);
this.pendingGuardrails.set(sessionId, {
resolve: (response) => {
clearTimeout(timeoutId);
this.pendingGuardrails.delete(sessionId);
resolve(response);
},
reject,
data: guardrailData
});
// Notify UI/human
this.notifyHuman(sessionId, guardrailData);
});
}
respondToGuardrail(sessionId, prompt, shouldResume = true) {
const pending = this.pendingGuardrails.get(sessionId);
if (pending) {
pending.resolve({
actionType: "guardrail",
prompt,
newState: shouldResume ? "resume" : "stop"
});
}
}
notifyHuman(sessionId, data) {
console.log(`[${sessionId}] Human input needed:`, data.value);
// Send notification to UI, Slack, email, etc.
}
}
// Usage
const handler = new AsyncGuardrailHandler(30000);
socket.on("message", async (data) => {
if (data.type === "guardrail_trigger") {
try {
const response = await handler.handle(session.sessionId, data.data);
socket.emit("message", response);
} catch (error) {
console.error("Guardrail handling failed:", error);
// Stop the task
socket.emit("message", {
actionType: "state",
newState: "stop"
});
}
}
});
// Human responds via UI
app.post("/api/respond-guardrail", (req, res) => {
const { sessionId, response, shouldResume } = req.body;
handler.respondToGuardrail(sessionId, response, shouldResume);
res.json({ success: true });
});
```
***
## Best Practices
### 1. Never Hardcode Sensitive Data
Don't put credentials directly in code:
```javascript theme={null}
// Bad
socket.emit("message", {
actionType: "guardrail",
prompt: "Username: admin, Password: admin123",
newState: "resume"
});
// Good
socket.emit("message", {
actionType: "guardrail",
prompt: `Username: ${process.env.USERNAME}, Password: ${process.env.PASSWORD}`,
newState: "resume"
});
```
### 2. Implement Timeouts
Always set timeouts for human intervention:
```javascript theme={null}
const GUARDRAIL_TIMEOUT = 60000; // 1 minute
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Timeout")), GUARDRAIL_TIMEOUT)
);
const responsePromise = waitForHumanResponse(sessionId);
try {
const response = await Promise.race([responsePromise, timeoutPromise]);
socket.emit("message", response);
} catch (error) {
console.log("Timeout - stopping task");
socket.emit("message", { actionType: "state", newState: "stop" });
}
```
### 3. Log All Guardrails
Track guardrail occurrences for debugging and improvement:
```javascript theme={null}
function logGuardrail(sessionId, guardrailData, response) {
console.log({
timestamp: new Date().toISOString(),
sessionId,
guardrailType: guardrailData.type,
guardrailMessage: guardrailData.value,
responseType: response ? "automated" : "manual",
response: response?.prompt
});
// Send to logging service
analytics.track("guardrail_triggered", {
sessionId,
type: guardrailData.type,
automated: !!response
});
}
```
### 4. Provide Clear Responses
Be specific in your guardrail responses:
```javascript theme={null}
// Bad - vague
socket.emit("message", {
actionType: "guardrail",
prompt: "Yes, do it",
newState: "resume"
});
// Good - specific
socket.emit("message", {
actionType: "guardrail",
prompt: "Select the product titled 'Logitech K380' from the search results",
newState: "resume"
});
```
***
Provide credentials upfront to avoid guardrails
Take direct control for CAPTCHA and complex inputs
Pause, resume, stop, and terminate tasks
Runtime rules that can trigger guardrails automatically
# Manual Interaction
Source: https://docs.webrun.ai/usage-guides/manual-interaction
Take control of the browser with clicks, typing, and keyboard inputs
Manual interaction lets you take direct control of the browser session. Use this when the AI agent gets stuck, when handling sensitive credentials, or when you need precise control over specific actions.
## Coordinate System
The browser viewport is 1024×600 pixels. The origin (0,0) is at the top-left. Add 155 pixels to your Y coordinate to account for browser chrome (address bar, tabs).
**Clickable area:** 1024×445 pixels (after accounting for 155px chrome offset)
If you're displaying the stream at a different size, scale coordinates proportionally:
```javascript theme={null}
function scaleCoords(clientX, clientY, displayWidth, displayHeight) {
const serverWidth = 1024;
const serverHeight = 600;
const yOffset = 155; // Browser chrome
return {
x: Math.round((clientX / displayWidth) * serverWidth),
y: Math.round((clientY / displayHeight) * serverHeight) + yOffset
};
}
```
***
## Taking Control
### takeOverControl
Pause the AI agent and enable manual mode:
```bash REST theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "SESSION_ID",
"message": {
"actionType": "interaction",
"action": { "type": "takeOverControl" }
}
}'
```
```javascript WebSocket theme={null}
socket.emit("message", {
actionType: "interaction",
action: { type: "takeOverControl" }
});
```
The current task pauses automatically. Perform manual actions, then release control to let the agent continue.
***
### releaseControl
Return control to the AI agent:
```bash REST theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "SESSION_ID",
"message": {
"actionType": "interaction",
"action": { "type": "releaseControl" }
}
}'
```
```javascript WebSocket theme={null}
socket.emit("message", {
actionType: "interaction",
action: { "type": "releaseControl" }
});
```
***
## Interaction Actions
### Click
Click at specific coordinates:
```javascript theme={null}
{
"actionType": "interaction",
"action": {
"type": "CLICK",
"x": 500, // 0-1024
"y": 300 // 155-755 (with chrome offset)
}
}
```
***
### Type
Type text into the currently focused element:
```javascript theme={null}
{
"actionType": "interaction",
"action": {
"type": "TYPE",
"text": "Hello world",
"humanLike": true // Optional: simulate human typing speed
}
}
```
Set `humanLike: true` to simulate realistic typing speed and patterns. This helps avoid detection on sites with anti-bot measures.
***
### Key Press
Press a single key or key combination:
```javascript theme={null}
{
"actionType": "interaction",
"action": {
"type": "KEY_PRESS",
"key": "Enter"
}
}
```
**Common keys:**
* `Enter`, `Escape`, `Tab`, `Backspace`, `Delete`
* `ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight`
* `PageUp`, `PageDown`, `Home`, `End`
* Single characters: `a`, `b`, `1`, `2`, etc.
***
## Common Patterns
### Manual Login with 2FA
```javascript theme={null}
// Take control
socket.emit("message", {
actionType: "interaction",
action: { type: "takeOverControl" }
});
// Click username field
socket.emit("message", {
actionType: "interaction",
action: { type: "CLICK", x: 400, y: 300 }
});
// Type username
socket.emit("message", {
actionType: "interaction",
action: { type: "TYPE", text: "user@example.com", humanLike: true }
});
// Tab to password field
socket.emit("message", {
actionType: "interaction",
action: { type: "KEY_PRESS", key: "Tab" }
});
// Type password
socket.emit("message", {
actionType: "interaction",
action: { type: "TYPE", text: "secretPassword123", humanLike: true }
});
// Submit
socket.emit("message", {
actionType: "interaction",
action: { type: "KEY_PRESS", key: "Enter" }
});
// Wait for 2FA prompt, user solves it manually via video stream
// Release control after 2FA is complete
socket.emit("message", {
actionType: "interaction",
action: { type: "releaseControl" }
});
```
***
### Dropdown Navigation
```javascript theme={null}
// Open dropdown
socket.emit("message", {
actionType: "interaction",
action: { type: "CLICK", x: 500, y: 350 }
});
// Navigate with arrow keys
socket.emit("message", {
actionType: "interaction",
action: { type: "KEY_PRESS", key: "ArrowDown" }
});
socket.emit("message", {
actionType: "interaction",
action: { type: "KEY_PRESS", key: "ArrowDown" }
});
// Select
socket.emit("message", {
actionType: "interaction",
action: { type: "KEY_PRESS", key: "Enter" }
});
```
***
### Responding to Guardrails
```javascript theme={null}
socket.on("message", (data) => {
if (data.type === "guardrail_trigger" &&
data.data.value.includes("CAPTCHA")) {
// Take control for manual solving
socket.emit("message", {
actionType: "interaction",
action: { type: "takeOverControl" }
});
// User solves CAPTCHA via video stream
// Once done, release control and resume
document.getElementById("captcha-solved").onclick = () => {
socket.emit("message", {
actionType: "interaction",
action: { type: "releaseControl" }
});
socket.emit("message", {
actionType: "guardrail",
prompt: "CAPTCHA solved, continue",
newState: "resume"
});
};
}
});
```
***
## Complete Example with Video Stream
```javascript theme={null}
import { io } from "socket.io-client";
// Create session
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
task: {
prompt: "Go to login page",
startingUrl: "https://example.com/login"
}
})
}).then(r => r.json());
// Setup video stream
const iframe = document.createElement("iframe");
iframe.src = session.streaming.webViewURL;
iframe.width = 1024;
iframe.height = 600;
document.body.appendChild(iframe);
// Connect WebSocket
const socket = io("https://api.webrun.ai", {
auth: { sessionId: session.sessionId },
transports: ["websocket"]
});
// Take control when ready
socket.on("connect", () => {
socket.emit("message", {
actionType: "interaction",
action: { type: "takeOverControl" }
});
});
// Setup click handler
const canvas = document.getElementById("clickable-overlay");
canvas.addEventListener("click", (e) => {
const rect = canvas.getBoundingClientRect();
const coords = scaleCoords(
e.clientX - rect.left,
e.clientY - rect.top,
rect.width,
rect.height
);
socket.emit("message", {
actionType: "interaction",
action: { type: "CLICK", x: coords.x, y: coords.y }
});
});
// Release control when done
document.getElementById("done-button").addEventListener("click", () => {
socket.emit("message", {
actionType: "interaction",
action: { type: "releaseControl" }
});
// Continue with next task
socket.emit("message", {
actionType: "newTask",
newState: "start",
prompt: "Complete the checkout process"
});
});
function scaleCoords(clientX, clientY, displayWidth, displayHeight) {
return {
x: Math.round((clientX / displayWidth) * 1024),
y: Math.round((clientY / displayHeight) * 600) + 155
};
}
```
***
## Troubleshooting
| Issue | Solution |
| -------------------------- | ----------------------------------------------- |
| Clicks not registering | Verify Y offset (155px) is added to coordinates |
| Clicking wrong location | Check coordinate scaling function |
| Typing not working | Click element first to ensure it's focused |
| Actions happening too fast | Add delays between actions (500ms recommended) |
***
Setup video streaming for visual feedback
Respond when the agent needs help
# Multi-Task Workflows
Source: https://docs.webrun.ai/usage-guides/multi-task-workflows
Learn how to create persistent sessions and send multiple tasks sequentially
## Overview
Multi-task workflows allow you to reuse a single browser session for multiple sequential tasks. This is more efficient than creating a new session for each task, as the browser state persists between tasks.
**When to use:**
* Multiple related tasks on the same website
* Workflows that build on previous actions (e.g., login → search → checkout)
* Scenarios where maintaining browser state (cookies, local storage) is important
For workflows that span multiple sessions (e.g., daily recurring tasks that need to stay logged in), use [environments](/environments/overview) to persist cookies, files, and browser data between sessions.
**When not to use:**
* Single, isolated tasks (use `/start/run-task` instead)
* Unrelated tasks across different websites
***
## Creating Persistent Sessions
Use the `/start/start-session` endpoint to create a session that remains active for multiple tasks.
```bash theme={null}
curl -X POST https://api.webrun.ai/start/start-session \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"mode": "default",
"task": {
"prompt": "Go to amazon.com",
"startingUrl": "https://amazon.com",
"maxDuration": 300000
}
}'
```
**Response:**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"socketURL": "https://api.webrun.ai",
"streaming": {
"webRTCURL": "https://a1b2c3d4e5f6.webrun.ai/whep",
"webViewURL": "https://a1b2c3d4e5f6.webrun.ai",
"dimensions": { "width": 1024, "height": 600 }
},
"initialPrompt": "Go to amazon.com",
"expiresIn": 300000,
"balance": 12.50,
"message": "Connect to instance using sessionId in auth"
}
```
Save the `sessionId` from the response: you'll need it for all follow-up tasks.
***
## Sending Follow-Up Tasks
After creating a session, send additional tasks using the `/start/send-message` endpoint with `actionType: "newTask"`.
```bash REST API theme={null}
curl -X POST https://api.webrun.ai/start/send-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"sessionId": "SESSION_ID",
"message": {
"actionType": "newTask",
"newState": "start",
"prompt": "Now add the first item to cart"
}
}'
```
```javascript WebSocket theme={null}
socket.emit("message", {
actionType: "newTask",
newState: "start",
prompt: "Now add the first item to cart",
maxDuration: 60000
});
socket.on("message", (data) => {
if (data.type === "task_completed") {
console.log("Task done:", data.data);
}
});
```
**Response (completed within 50 seconds):**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"result": {
"type": "task_completed",
"data": { "message": "Added item to cart" }
}
}
```
**Response (still running):**
```json theme={null}
{
"success": true,
"sessionId": "a1b2c3d4e5f6",
"taskId": "x9y8z7w6v5u4",
"pending": true,
"pollUrl": "https://api.webrun.ai/task/a1b2c3d4e5f6/x9y8z7w6v5u4"
}
```
***
## Complete Working Example
This example demonstrates a complete multi-task workflow: creating a session, sending multiple tasks, polling for results, and terminating the session.
```javascript theme={null}
const API_KEY = "YOUR_API_KEY";
const BASE = "https://api.webrun.ai";
async function runMultiTaskWorkflow() {
// 1. Create session
const session = await fetch(`${BASE}/start/start-session`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
mode: "default",
task: {
prompt: "Go to amazon.com",
startingUrl: "https://amazon.com"
}
})
}).then(r => r.json());
console.log("Session created:", session.sessionId);
// 2. Send follow-up task
const task1 = await fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId: session.sessionId,
message: {
actionType: "newTask",
newState: "start",
prompt: "Search for 'wireless keyboard'"
}
})
}).then(r => r.json());
// 3. Poll if pending
if (task1.pending) {
const result = await pollForResult(session.sessionId, task1.taskId);
console.log("Task 1 result:", result);
}
// 4. Send another task
const task2 = await fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId: session.sessionId,
message: {
actionType: "newTask",
newState: "start",
prompt: "Add the first result to cart"
}
})
}).then(r => r.json());
if (task2.pending) {
const result = await pollForResult(session.sessionId, task2.taskId);
console.log("Task 2 result:", result);
}
// 5. Terminate when done
await fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId: session.sessionId,
message: { actionType: "state", newState: "terminate" }
})
});
console.log("Session terminated");
}
async function pollForResult(sessionId, taskId) {
const maxAttempts = 60;
const interval = 2000;
for (let i = 0; i < maxAttempts; i++) {
const res = await fetch(`${BASE}/task/${sessionId}/${taskId}`, {
headers: { "Authorization": `Bearer ${API_KEY}` }
});
const data = await res.json();
if (data.type === "task_completed") return data;
if (data.type === "guardrail_trigger") throw new Error(`Guardrail: ${data.data.value}`);
if (data.status === "failed") throw new Error(data.error);
if (data.pending) {
await new Promise(r => setTimeout(r, interval));
continue;
}
return data;
}
throw new Error("Polling timeout");
}
runMultiTaskWorkflow();
```
***
## Single vs Multi-Task Comparison
### Use `/start/run-task` for Single Tasks
When you only need to execute one task and don't need session persistence:
```bash theme={null}
curl -X POST https://api.webrun.ai/start/run-task \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"task": {
"prompt": "Search Google for Anthropic and return the first result"
}
}'
```
* Session automatically terminates when task completes
* No need to manage `sessionId`
* `terminateOnCompletion: true` is set automatically
* More cost-effective for isolated tasks
### Use `/start/start-session` for Multi-Task Workflows
When you need to:
* Execute multiple related tasks
* Maintain browser state between tasks
* Potentially interact manually between tasks
* Have control over session lifecycle
```bash theme={null}
# Create session
POST /start/start-session
# Send task 1
POST /start/send-message { actionType: "newTask", ... }
# Send task 2
POST /start/send-message { actionType: "newTask", ... }
# Terminate when done
POST /start/send-message { actionType: "state", newState: "terminate" }
```
***
## Session Parameters
Configure your session behavior with these parameters:
**Top-level parameters:**
| Parameter | Type | Default | Description |
| --------------- | ------ | --------- | -------------------------------------------------- |
| `mode` | string | "default" | Session mode (currently only "default" supported) |
| `environmentId` | string | null | [Environment](/environments/overview) ID to attach |
| `task` | object | null | Initial task configuration (see below) |
**task parameters:**
| Parameter | Type | Default | Description |
| ----------------------- | --------- | ------- | ------------------------------------------------------------------------- |
| `prompt` | string | "" | Initial task description (can be empty for sessions without initial task) |
| `startingUrl` | string | null | Starting URL (e.g., `"https://amazon.com"`) |
| `maxDuration` | number | 300000 | Max task duration in ms (default and max: 5 minutes) |
| `maxInputTokens` | number | 100000 | Max input tokens for AI model |
| `maxOutputTokens` | number | 100000 | Max output tokens for AI model |
| `terminateOnCompletion` | boolean | false | Auto-terminate after first task completes |
| `outputType` | string | "text" | Output format: `"text"`, `"structured_json"`, or `"structured_csv"` |
| `outputSchema` | object | null | JSON Schema for structured output |
| `files` | string\[] | \[] | File IDs to attach to the task ([details](/environments/file-uploads)) |
**Example with parameters:**
```json theme={null}
{
"mode": "default",
"task": {
"prompt": "Search for wireless keyboards",
"startingUrl": "https://amazon.com",
"maxDuration": 180000,
"maxInputTokens": 50000,
"maxOutputTokens": 50000,
"terminateOnCompletion": false
}
}
```
* `maxDuration` is the max task duration (default and max: 5 minutes). Session inactivity timeout is fixed at 5 minutes
* `prompt` can be empty if you plan to send tasks later via `/start/send-message`
* Always terminate sessions when done to avoid unnecessary charges
***
## Best Practices
### 1. Always Terminate Sessions
Don't forget to terminate sessions when your workflow completes:
```javascript theme={null}
// At the end of your workflow
await fetch(`${BASE}/start/send-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId: session.sessionId,
message: { actionType: "state", newState: "terminate" }
})
});
```
Or use `terminateOnCompletion` on your final task:
```javascript theme={null}
message: {
actionType: "newTask",
newState: "start",
prompt: "Final task",
terminateOnCompletion: true
}
```
### 2. Handle Errors Gracefully
Always check for errors and handle guardrails:
```javascript theme={null}
const result = await pollForResult(sessionId, taskId);
if (result.type === "guardrail_trigger") {
// Handle guardrail - see Handling Guardrails guide
console.log("Guardrail:", result.data.value);
} else if (result.status === "failed") {
// Handle error
console.error("Task failed:", result.error);
}
```
### 3. Poll with Reasonable Intervals
Don't poll too frequently:
```javascript theme={null}
// Good: 2-second intervals
await new Promise(r => setTimeout(r, 2000));
// Bad: 100ms intervals (wastes requests)
await new Promise(r => setTimeout(r, 100));
```
### 4. Use WebSocket for Real-Time Updates
For better UX and efficiency, consider WebSocket instead of polling:
```javascript theme={null}
socket.on("message", (data) => {
if (data.type === "task_completed") {
console.log("Task done:", data.data);
} else if (data.type === "guardrail_trigger") {
console.log("Guardrail:", data.data.value);
}
});
```
***
Pause, resume, stop, and terminate tasks
Respond to agent requests for input
Persist browser data and files across sessions
Upload files for the agent to use in sessions
# Proxies
Source: https://docs.webrun.ai/usage-guides/proxies
Route browser sessions through proxy servers for geographic targeting and IP management
Route your browser sessions through proxy servers to control the geographic location and IP address of your automation.
***
## Proxy Levels
Control where the proxy is applied using the `level` parameter.
| Level | Description | Pros | Cons |
| -------- | ----------------------------------------------------------------- | ----------------- | --------------------------------------------- |
| `system` | Applied at the system level: the instance reboots with the new IP | No IP leakage | Slower cold start |
| `chrome` | Applied directly to Chrome | Faster cold start | Can leak IP on some edge cases (e.g., WebRTC) |
When `level` is omitted, the proxy is routed to the best available connection that matches the country.
```json System-level proxy theme={null}
{
"proxy": {
"source": "WebRun",
"country": "US",
"level": "system"
}
}
```
```json Chrome-level proxy theme={null}
{
"proxy": {
"source": "WebRun",
"country": "US",
"level": "chrome"
}
}
```
When using the `system` level, expect additional cold-start latency as the instance reboots with the new IP. The `chrome` level avoids this reboot but may expose the original IP in edge cases such as WebRTC connections.
***
## Proxy Modes
### WebRun-Managed Proxies
Specify a country and WebRun assigns a proxy from its residential pool. Charged at **\$2 per GB** of data transfer.
Set `country` to any [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code, or `"random"` to let WebRun pick a location.
```json run-task theme={null}
{
"proxy": {
"source": "WebRun",
"country": "GB"
},
"task": {
"prompt": "Check product prices on amazon.co.uk",
"startingUrl": "https://amazon.co.uk"
}
}
```
```json start-session (nested format) theme={null}
{
"proxy": {
"source": "WebRun",
"country": "GB"
},
"task": {
"prompt": "Check product prices on amazon.co.uk",
"startingUrl": "https://amazon.co.uk"
}
}
```
Setting `country` to `"random"`:
```json theme={null}
{
"proxy": {
"source": "WebRun",
"country": "random"
}
}
```
### Custom Proxies
Bring your own proxy server. No additional charge from WebRun: you pay your proxy provider directly. The `username` and `password` fields are optional for proxies that don't require authentication.
**HTTP proxy:**
```json theme={null}
{
"proxy": {
"source": "custom",
"type": "http",
"host": "proxy.example.com",
"port": "8080",
"username": "user",
"password": "pass"
}
}
```
**SOCKS proxy:**
```json theme={null}
{
"proxy": {
"source": "custom",
"type": "socks",
"host": "proxy.example.com",
"port": "1080"
}
}
```
### Disabling Proxy
To explicitly run without a proxy (the default), set `proxy` to `null` or omit it:
```json theme={null}
{
"proxy": null
}
```
***
## Full Examples
### Single-task session with WebRun proxy
```bash theme={null}
curl -X POST https://api.webrun.ai/start/run-task \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"proxy": {
"source": "WebRun",
"country": "DE"
},
"task": {
"prompt": "Go to google.de and search for Berlin restaurants",
"startingUrl": "https://google.de"
}
}'
```
### Persistent session with custom proxy
```bash theme={null}
curl -X POST https://api.webrun.ai/start/start-session \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"environmentId": "683a1f2e4b0c1d2e3f4a5b6c",
"proxy": {
"source": "custom",
"type": "http",
"host": "proxy.example.com",
"port": "8080",
"username": "user",
"password": "pass"
},
"task": {
"prompt": "Navigate to the dashboard",
"startingUrl": "https://app.example.com"
}
}'
```
The `proxy` field is a top-level session parameter, alongside `environmentId` and `task`. It is not nested inside `task`.
***
## Pricing
| Proxy Mode | Cost |
| ----------------------- | --------------------------- |
| WebRun-managed | \$2 per GB of data transfer |
| Custom (bring your own) | No additional WebRun charge |
Data transfer is measured across the entire session. Usage is visible in your [dashboard](https://app.webrun.ai/usage).
***
## Best Practices
* **Choose the closest country** to your target website's servers to minimize latency.
* **Use `"random"` sparingly**: a specific country gives more predictable results for locale-sensitive sites.
* **Use custom proxies for high-bandwidth tasks** (large file downloads, video scraping) to avoid per-GB charges.
* **Combine with environments**: pair a proxy with an [environment](/environments/overview) to maintain consistent cookies and browser state across proxied sessions.
* **Account for cold-start**: the 2-3 second proxy setup time is a one-time cost per session, not per task.
***
Session configuration and lifecycle
Full proxy parameter reference
Proxy and compute pricing details
Provide credentials for authenticated sites
# Secrets
Source: https://docs.webrun.ai/usage-guides/secrets
Provide credentials securely to the agent for website authentication during task execution
## Overview
When your agent needs to log into websites or authenticate with services during task execution, you can provide credentials using the `secrets` parameter. Secrets are matched to websites by domain pattern, so the agent uses the right credentials for each site it visits.
Secrets are **never stored** in a database or persisted anywhere. They are only loaded and attached to the active session, then **immediately discarded** once the session is destroyed.
This approach eliminates the need for [guardrail-based credential handling](/usage-guides/handling-guardrails#1-login-credentials), where the agent pauses and waits for you to provide login details mid-task. With secrets, the agent can authenticate automatically without interruption.
***
## Schema
| Field | Type | Required | Description |
| ------------------ | -------- | -------- | ------------------------------------------------------------------------------ |
| `secrets` | `array` | No | Array of secret entries to provide credentials for websites |
| `secrets[].match` | `string` | Yes | Domain pattern to match (e.g. `*.salesforce.com`) or `all` to match every site |
| `secrets[].fields` | `object` | Yes | Key-value pairs of credential fields (e.g. `email`, `password`, `apiKey`) |
***
## Request Example
```javascript theme={null}
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
mode: "default",
task: {
prompt: "Log into Salesforce and export the open opportunities report",
maxDuration: 10,
maxInputTokens: 400000,
maxOutputTokens: 200000,
outputType: "structured_json",
outputSchema: {
type: "object",
properties: {
opportunities: {
type: "array",
items: {
type: "object",
properties: {
name: { type: "string" },
amount: { type: "number" },
stage: { type: "string" }
}
}
}
},
additionalProperties: false
},
secrets: [
{
match: "*.salesforce.com",
fields: {
email: "user@company.com",
password: "secretpass"
}
},
{
match: "all",
fields: {
email: "user@company.com",
password: "defaultpass"
}
}
]
}
})
}).then(r => r.json());
```
***
## How Matching Works
The `match` field determines which websites the credentials apply to:
| Pattern | Matches |
| ------------------ | ------------------------------------------------------------------------------------- |
| `*.salesforce.com` | Any subdomain of salesforce.com (e.g. `login.salesforce.com`, `myorg.salesforce.com`) |
| `github.com` | Exactly `github.com` |
| `all` | Any website the agent visits, used as a fallback |
When multiple secrets match a domain, the more specific pattern takes priority over `all`.
***
## Custom Fields
The `fields` object supports arbitrary key-value pairs. Use field names that correspond to the login form fields on the target website:
```json theme={null}
{
"match": "*.example.com",
"fields": {
"username": "admin",
"password": "secretpass",
"otp_secret": "JBSWY3DPEHPK3PXP",
"api_key": "sk-abc123"
}
}
```
***
## Security
Secrets are transmitted securely and are **never** included in task output or webhook payloads. They are only used by the agent during browser automation to fill in authentication forms.
Key security properties:
* **No persistence**: Secrets are never stored in a database or written to disk. They exist only in the session's memory.
* **Session-scoped**: Secrets are attached to the session at creation and immediately discarded when the session is destroyed.
* **Not in output**: Secrets never appear in task results, webhook payloads, or logs.
* **Encrypted in transit**: All API communication uses HTTPS/TLS.
***
## Secrets vs Guardrails
| Aspect | Secrets | Guardrails |
| --------------------------------- | ---------------------------------------- | ------------------------------------ |
| **When credentials are provided** | Upfront, at session creation | On-demand, when the agent asks |
| **Task interruption** | None: agent authenticates automatically | Task pauses until you respond |
| **Automation** | Fully automated | Requires a handler or human response |
| **Best for** | Known login targets, automated pipelines | Dynamic or unpredictable auth flows |
Use secrets when you know which sites the agent will authenticate with. Use [guardrails](/usage-guides/handling-guardrails) when you need to provide credentials interactively or handle unexpected login prompts.
***
## Best Practices
### Use Environment Variables
Never hardcode secrets in your source code:
```javascript theme={null}
// Bad
secrets: [{ match: "*.example.com", fields: { password: "hardcoded123" } }]
// Good
secrets: [{ match: "*.example.com", fields: { password: process.env.EXAMPLE_PASSWORD } }]
```
### Use Specific Patterns
Prefer specific domain patterns over `all` to limit credential exposure:
```javascript theme={null}
// Targeted: credentials only sent to Salesforce
secrets: [
{ match: "*.salesforce.com", fields: { email: "user@co.com", password: "pass" } }
]
// Fallback: use 'all' only when needed as a catch-all
secrets: [
{ match: "*.salesforce.com", fields: { email: "sf@co.com", password: "sfpass" } },
{ match: "all", fields: { email: "default@co.com", password: "defaultpass" } }
]
```
### Combine with terminateOnCompletion
For single-use authenticated tasks, terminate the session immediately after completion to ensure secrets are discarded as soon as possible:
```javascript theme={null}
{
"task": {
"prompt": "Log in and export the report",
"terminateOnCompletion": true,
"secrets": [
{ "match": "*.example.com", "fields": { "email": "user@co.com", "password": "pass" } }
]
}
}
```
***
Interactive credential handling when secrets aren't set
How guardrails work and when they trigger
Complete API parameter documentation
Reduce costs with session management
# Structured Output
Source: https://docs.webrun.ai/usage-guides/structured-output
Get structured, parseable data from AI agent tasks for downstream processing
## Overview
By default, AI agents return natural language responses in markdown format. To get structured data, use the `outputType` parameter to specify the desired format.
**Output Types:**
| Type | Description | Schema Format |
| ----------------- | --------------------------------- | --------------------- |
| `text` | Markdown formatted text (default) | Not required |
| `structured_json` | Validated JSON output | JSON Schema object |
| `structured_csv` | CSV formatted data | Array of column names |
When using `structured_json` or `structured_csv`, WebRun validates the output against your schema before returning it.
***
## Output Type: text
The default output type returns natural language responses formatted as markdown. No `outputSchema` is required.
### Request Example
```javascript theme={null}
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
mode: "default",
task: {
prompt: "Give me the latest prices of the top performing cryptos",
taskId: "3e0f4258511fc909775b9f1a74656004",
maxDuration: 5,
maxInputTokens: 400000,
maxOutputTokens: 200000,
outputType: "text"
}
})
}).then(r => r.json());
```
### Response
The response contains markdown-formatted text:
```json theme={null}
{
"success": true,
"type": "task_completed",
"data": {
"message": "## Top Cryptocurrency Prices\n\n| Name | Price |\n|------|-------|\n| Bitcoin | $95,360.97 |\n| Ethereum | $3,325.94 |\n...",
"prompt_tokens": 8500,
"completion_tokens": 2300,
"total_tokens": 10800
}
}
```
***
## Output Type: structured\_json
Use `structured_json` to get validated JSON output. The `outputSchema` parameter accepts a standard JSON Schema object that defines the expected response structure.
### Supported JSON Schema Types
* `string` - Text values
* `number` - Numeric values (integers and decimals)
* `boolean` - True/false values
* `object` - Nested objects with defined properties
* `array` - Arrays with defined item structure
### Request Example
```javascript theme={null}
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
mode: "default",
task: {
prompt: "Give me the latest prices of the top performing cryptos",
taskId: "2444180416485ba80be9f12ef51134dc",
maxDuration: 60,
maxInputTokens: 4000,
maxOutputTokens: 2000,
outputType: "structured_json",
outputSchema: {
type: "object",
properties: {
top: {
type: "array",
items: {
type: "object",
properties: {
name: { type: "string" },
price: { type: "string" }
}
}
}
},
additionalProperties: false
}
}
})
}).then(r => r.json());
```
### Response
The response is guaranteed to match your schema:
```json theme={null}
{
"success": true,
"type": "task_completed",
"data": {
"message": "{\"top\":[{\"name\":\"Bitcoin\",\"price\":\"$95,187.71\"},{\"name\":\"Ethereum\",\"price\":\"$3,319.17\"},{\"name\":\"Tether\",\"price\":\"$0.9995\"},{\"name\":\"XRP\",\"price\":\"$2.15\"},{\"name\":\"BNB\",\"price\":\"$942.50\"},{\"name\":\"Solana\",\"price\":\"$145.42\"},{\"name\":\"USDC\",\"price\":\"$0.9997\"},{\"name\":\"TRON\",\"price\":\"$0.3064\"},{\"name\":\"Dogecoin\",\"price\":\"$0.1482\"},{\"name\":\"Cardano\",\"price\":\"$0.4199\"}]}",
"prompt_tokens": 8500,
"completion_tokens": 2300,
"total_tokens": 10800
}
}
```
When using `outputType: "structured_json"`, the response is guaranteed to match your schema. The `data.message` field contains a valid JSON string that can be directly parsed.
***
## Output Type: structured\_csv
Use `structured_csv` to get CSV formatted output. The `outputSchema` parameter accepts an array of column names that define the CSV structure.
### Request Example
```javascript theme={null}
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
mode: "default",
task: {
prompt: "Give me the latest prices of the top performing cryptos",
taskId: "3e0f4258511fc909775b9f1a74656004",
maxDuration: 5,
maxInputTokens: 400000,
maxOutputTokens: 200000,
outputType: "structured_csv",
outputSchema: ["name", "price"]
}
})
}).then(r => r.json());
```
### Response
The response contains CSV formatted data with the specified columns:
```json theme={null}
{
"success": true,
"type": "task_completed",
"data": {
"message": "name,price\nBitcoin,$95,360.97\nEthereum,$3,325.94\nTether,$0.9994\nXRP,$2.16\nBNB,$943.70\nSolana,$145.38\nUSDC,$0.9996\nTRON,$0.3070\nDogecoin,$0.1483\nCardano,$0.4220",
"prompt_tokens": 8500,
"completion_tokens": 2300,
"total_tokens": 10800
}
}
```
### Parsing CSV Response
```javascript theme={null}
const result = await pollForResult(sessionId, taskId);
const csv = result.data.message;
const lines = csv.trim().split('\n');
const headers = lines[0].split(',');
const data = lines.slice(1).map(line => {
const values = line.match(/(".*?"|[^,]+)(?=\s*,|\s*$)/g);
const obj = {};
headers.forEach((header, i) => {
obj[header.trim()] = values[i]?.replace(/^"|"$/g, '').trim();
});
return obj;
});
console.log(data);
// [
// { name: "Bitcoin", price: "$95,360.97" },
// { name: "Ethereum", price: "$3,325.94" },
// ...
// ]
```
When using `outputType: "structured_csv"`, the `outputSchema` must be an array of column name strings. The first row of the output will be the header row containing these column names.
***
## Webhook Integration
Combine structured output with [webhooks](/usage-guides/webhooks) to automatically deliver validated data to your systems when tasks complete.
```javascript theme={null}
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
mode: "default",
task: {
prompt: "Extract product information from the page",
startingUrl: "https://example.com/product",
outputType: "structured_json",
outputSchema: {
type: "object",
properties: {
title: { type: "string" },
price: { type: "number" },
inStock: { type: "boolean" }
},
required: ["title", "price"],
additionalProperties: false
},
webhook: {
name: "Product Webhook",
url: "https://api.mysite.com/products",
auth: "Bearer token123",
submittedData: "ai_response"
}
}
})
}).then(r => r.json());
```
Use `submittedData: "ai_response"` to receive only the AI's output (text, structured\_json, or structured\_csv). See the [Webhooks guide](/usage-guides/webhooks) for complete documentation.
***
## Legacy Approach (Deprecated)
The approach of embedding schema descriptions in `prompt` is deprecated. Use the native `outputType` and `outputSchema` parameters instead for guaranteed validation and consistent output.
The examples below show the legacy pattern for reference. New implementations should use the [Native JSON Schema Support](#native-json-schema-support) documented above.
***
## JSON Output Pattern (Legacy)
The most common pattern for structured output is requesting JSON in your task description.
### Basic Example
```javascript theme={null}
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
task: {
prompt: `Go to amazon.com and search for "wireless keyboard".
Return the results as a JSON array with this format:
[
{ "title": "product name", "price": "19.99", "rating": "4.5" }
]`,
startingUrl: "https://amazon.com"
}
})
}).then(r => r.json());
```
**Expected Response:**
```json theme={null}
{
"success": true,
"type": "task_completed",
"data": {
"message": "[{\"title\":\"Logitech K380\",\"price\":\"29.99\",\"rating\":\"4.5\"},{\"title\":\"Arteck Wireless Keyboard\",\"price\":\"19.99\",\"rating\":\"4.3\"}]",
"prompt_tokens": 8500,
"completion_tokens": 2300,
"total_tokens": 10800
}
}
```
### Parsing the Result
```javascript theme={null}
async function getProductData(sessionId, taskId) {
// Poll for result
const result = await pollForResult(sessionId, taskId);
if (result.type === "task_completed") {
try {
// Parse JSON from message
const products = JSON.parse(result.data.message);
return products;
} catch (error) {
console.error("Failed to parse JSON:", error);
console.log("Raw message:", result.data.message);
return null;
}
}
return null;
}
// Usage
const products = await getProductData(session.sessionId, task.taskId);
console.log(products);
// [
// { title: "Logitech K380", price: "29.99", rating: "4.5" },
// { title: "Arteck Wireless Keyboard", price: "19.99", rating: "4.3" }
// ]
```
***
## Array Results
Request arrays for lists of items.
### Example: Product Search
```javascript theme={null}
const prompt = `
Search Google for "best mechanical keyboards 2024".
Extract the top 5 results and return as a JSON array:
[
{
"title": "page title",
"url": "https://...",
"snippet": "brief description"
}
]
`;
const task = await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId: session.sessionId,
message: {
actionType: "newTask",
newState: "start",
prompt
}
})
}).then(r => r.json());
```
***
## Complex Nested Structures
Request nested JSON for complex data.
### Example: E-commerce Product Details
```javascript theme={null}
const prompt = `
Go to the Amazon product page at [URL].
Extract the following information and return as JSON:
{
"product": {
"title": "product name",
"price": "19.99",
"currency": "USD",
"inStock": true,
"rating": {
"stars": 4.5,
"count": 1234
},
"images": ["url1", "url2"],
"features": ["feature 1", "feature 2"],
"specifications": {
"brand": "...",
"model": "...",
"dimensions": "..."
}
}
}
`;
const result = await sendTaskAndWait(session.sessionId, prompt);
const productData = JSON.parse(result.data.message);
console.log(productData.product.title);
console.log(productData.product.rating.stars);
```
***
## Validation with Zod (TypeScript)
Use Zod for runtime validation and type safety.
### Install Zod
```bash theme={null}
npm install zod
```
### Define Schema
```typescript theme={null}
import { z } from "zod";
// Define expected structure
const ProductSchema = z.object({
title: z.string(),
price: z.string(),
rating: z.string(),
url: z.string().url(),
inStock: z.boolean()
});
const ProductArraySchema = z.array(ProductSchema);
// Type inference
type Product = z.infer;
```
### Validate Response
```typescript theme={null}
async function getValidatedProducts(sessionId: string, taskId: string): Promise {
const result = await pollForResult(sessionId, taskId);
if (result.type !== "task_completed") {
throw new Error("Task not completed");
}
try {
// Parse JSON
const rawData = JSON.parse(result.data.message);
// Validate with Zod
const products = ProductArraySchema.parse(rawData);
return products; // Type-safe products array
} catch (error) {
if (error instanceof z.ZodError) {
console.error("Validation failed:", error.errors);
throw new Error(`Invalid product data: ${error.message}`);
}
throw error;
}
}
// Usage (TypeScript knows the shape)
const products = await getValidatedProducts(sessionId, taskId);
products.forEach(product => {
console.log(product.title); // Type-safe
console.log(product.price); // Type-safe
});
```
***
## Handling Parse Errors
Sometimes the AI returns malformed JSON. Implement fallback strategies:
### Strategy 1: Extract JSON from Text
```javascript theme={null}
function extractJSON(text) {
// Try direct parse first
try {
return JSON.parse(text);
} catch (error) {
// Try to find JSON within text
const jsonMatch = text.match(/\[[\s\S]*\]|\{[\s\S]*\}/);
if (jsonMatch) {
try {
return JSON.parse(jsonMatch[0]);
} catch (innerError) {
console.error("Failed to extract JSON:", innerError);
}
}
}
return null;
}
// Usage
const result = await pollForResult(sessionId, taskId);
const data = extractJSON(result.data.message);
if (data) {
console.log("Parsed:", data);
} else {
console.log("Could not parse, raw response:", result.data.message);
}
```
### Strategy 2: Request Re-formatting
```javascript theme={null}
async function getStructuredDataWithRetry(sessionId, originalTaskId) {
const result = await pollForResult(sessionId, originalTaskId);
// Try to parse
try {
return JSON.parse(result.data.message);
} catch (error) {
console.log("Initial parse failed, requesting reformatting...");
// Send follow-up task to reformat
const reformatTask = await fetch("https://api.webrun.ai/start/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
sessionId,
message: {
actionType: "newTask",
newState: "start",
prompt: `Take the previous response and format it as valid JSON: ${result.data.message}`
}
})
}).then(r => r.json());
const reformatResult = await pollForResult(sessionId, reformatTask.taskId);
return JSON.parse(reformatResult.data.message);
}
}
```
***
## Best Practices
### 1. Be Specific in Schema Description
```javascript theme={null}
// Bad - vague
prompt: "Return product info as JSON"
// Good - explicit schema
prompt: `
Return product information as JSON with this exact structure:
{
"title": "string",
"price": "number as string (e.g., '29.99')",
"inStock": "boolean (true/false)",
"rating": "number as string (e.g., '4.5')"
}
`
```
### 2. Request Array Length Limits
Prevent unexpectedly large responses:
```javascript theme={null}
prompt: `
Search for wireless keyboards and return the top 10 results (no more than 10) as JSON array:
[
{ "title": "...", "price": "...", "url": "..." }
]
`
```
### 3. Specify Data Types Clearly
```javascript theme={null}
prompt: `
Return product data as JSON:
{
"title": "string",
"price": "string in format '19.99' (no currency symbol)",
"inStock": "boolean (true or false, not string)",
"rating": "number (e.g., 4.5, not string)",
"reviewCount": "integer (e.g., 123, not string)"
}
`
```
### 4. Handle Missing Data
Specify how to handle missing fields:
```javascript theme={null}
prompt: `
Return product data as JSON:
{
"title": "string (required)",
"price": "string or null if not available",
"rating": "number or null if no ratings",
"inStock": "boolean or null if unknown"
}
`
```
### 5. Use TypeScript for Type Safety
```typescript theme={null}
interface Product {
title: string;
price: string | null;
rating: number | null;
inStock: boolean | null;
}
async function getProducts(sessionId: string, taskId: string): Promise {
const result = await pollForResult(sessionId, taskId);
const products: Product[] = JSON.parse(result.data.message);
return products;
}
```
***
## Complete Example: Product Comparison
```javascript theme={null}
const API_KEY = "YOUR_API_KEY";
const BASE = "https://api.webrun.ai";
async function compareProducts(searchQuery) {
// 1. Create session
const session = await fetch(`${BASE}/start/start-session`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
task: {
prompt: `
Go to Amazon and search for "${searchQuery}".
Return the top 5 results as a JSON array with this structure:
[
{
"title": "product title",
"price": "price as string without currency symbol (e.g., '29.99')",
"rating": "average rating as number (e.g., 4.5)",
"reviewCount": "number of reviews as integer",
"url": "product URL",
"isPrime": "boolean indicating Prime eligibility"
}
]
Return ONLY the JSON array, no additional text.
`,
startingUrl: "https://amazon.com",
terminateOnCompletion: true
}
})
}).then(r => r.json());
console.log("Session created:", session.sessionId);
// 2. Poll for result
const result = await pollForResult(session.sessionId, session.taskId);
// 3. Parse and validate
try {
const products = JSON.parse(result.data.message);
// Validate structure
if (!Array.isArray(products)) {
throw new Error("Expected array of products");
}
// Process results
const processed = products.map(p => ({
...p,
price: parseFloat(p.price),
pricePerStar: (parseFloat(p.price) / p.rating).toFixed(2)
}));
// Sort by value (price per rating star)
processed.sort((a, b) => a.pricePerStar - b.pricePerStar);
console.log("Best value products:");
processed.forEach((p, i) => {
console.log(`${i + 1}. ${p.title}`);
console.log(` Price: $${p.price}, Rating: ${p.rating} (${p.reviewCount} reviews)`);
console.log(` Value: $${p.pricePerStar} per star`);
console.log(` URL: ${p.url}`);
console.log();
});
return processed;
} catch (error) {
console.error("Failed to parse product data:", error);
console.log("Raw response:", result.data.message);
return null;
}
}
async function pollForResult(sessionId, taskId) {
const maxAttempts = 60;
const interval = 2000;
for (let i = 0; i < maxAttempts; i++) {
const res = await fetch(`${BASE}/task/${sessionId}/${taskId}`, {
headers: { "Authorization": `Bearer ${API_KEY}` }
});
const data = await res.json();
if (data.type === "task_completed") return data;
if (data.type === "guardrail_trigger") throw new Error(`Guardrail: ${data.data.value}`);
if (data.status === "failed") throw new Error(data.error);
if (data.pending) {
await new Promise(r => setTimeout(r, interval));
continue;
}
return data;
}
throw new Error("Polling timeout");
}
// Run comparison
compareProducts("wireless mechanical keyboard");
```
***
## CSV Output
For tabular data, CSV can be simpler than JSON:
```javascript theme={null}
const prompt = `
Search Amazon for "standing desk" and return the top 10 results as CSV with these columns:
title,price,rating,reviewCount,url
Example:
"FlexiSpot Standing Desk","299.99","4.5","2341","https://..."
"FEZIBO Electric Desk","249.99","4.3","1823","https://..."
Return ONLY the CSV data with header row, no additional text.
`;
// Parse CSV
const result = await pollForResult(sessionId, taskId);
const csv = result.data.message;
const lines = csv.trim().split('\n');
const headers = lines[0].split(',');
const products = lines.slice(1).map(line => {
const values = line.match(/(".*?"|[^,]+)(?=\s*,|\s*$)/g);
const obj = {};
headers.forEach((header, i) => {
obj[header.trim()] = values[i].replace(/^"|"$/g, '').trim();
});
return obj;
});
console.log(products);
```
***
Receive automated notifications when tasks complete
Chain tasks to build complex data pipelines
# Video Streaming
Source: https://docs.webrun.ai/usage-guides/video-streaming
Watch browser sessions in real-time via WebRTC or browser player
## Overview
When you create a session, WebRun returns streaming URLs that allow you to watch the browser in real-time:
```json theme={null}
{
"streaming": {
"webRTCURL": "https://a1b2c3d4e5f6.webrun.ai/whep",
"webViewURL": "https://a1b2c3d4e5f6.webrun.ai",
"dimensions": { "width": 1024, "height": 600 }
}
}
```
### Two Options
| Method | Use Case | Complexity |
| -------------- | ---------------------------------------- | ---------- |
| **webViewURL** | Browser-based player, simple embed | Low |
| **webRTCURL** | Custom WebRTC integration, lower latency | Medium |
***
## Option 1: Browser Player (Recommended)
The simplest way to display a session, just embed the URL in an iframe:
```html theme={null}
```
**Benefits:**
* No WebRTC code needed
* Works in all modern browsers
* Automatic reconnection handling
* Built-in controls
**When to use:** Most applications, especially dashboards and monitoring UIs.
### React Example
```javascript theme={null}
import { useState, useEffect } from 'react';
function SessionViewer({ sessionId, streamingUrl }) {
return (
);
}
// Usage
function App() {
const [session, setSession] = useState(null);
useEffect(() => {
async function createSession() {
const response = await fetch('https://api.webrun.ai/start/start-session', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
task: {
prompt: 'Go to example.com',
startingUrl: 'https://example.com'
}
})
});
const data = await response.json();
setSession(data);
}
createSession();
}, []);
if (!session) return Loading...
;
return ;
}
```
***
## Option 2: WebRTC Integration (Advanced)
For custom video players or lower latency requirements.
### Quick Setup
```javascript theme={null}
async function connectStream(webRTCURL, videoElement) {
const pc = new RTCPeerConnection({
iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
});
// Receive video/audio
pc.addTransceiver("video", { direction: "recvonly" });
pc.addTransceiver("audio", { direction: "recvonly" });
// Attach tracks to video element
pc.ontrack = (e) => {
if (!videoElement.srcObject) {
videoElement.srcObject = new MediaStream();
}
videoElement.srcObject.addTrack(e.track);
};
// Create offer
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
// Wait for ICE gathering
await new Promise((resolve) => {
if (pc.iceGatheringState === "complete") resolve();
else pc.onicegatheringstatechange = () => {
if (pc.iceGatheringState === "complete") resolve();
};
});
// Send to WHEP server
const response = await fetch(webRTCURL, {
method: "POST",
headers: { "Content-Type": "application/sdp" },
body: pc.localDescription.sdp
});
if (!response.ok) {
throw new Error(`WHEP error: ${response.status}`);
}
const answer = await response.text();
await pc.setRemoteDescription({ type: "answer", sdp: answer });
return pc;
}
// Usage
const video = document.getElementById("stream");
const pc = await connectStream(session.streaming.webRTCURL, video);
```
**When to use:** Building custom video players, need ultra-low latency, advanced integration requirements.
***
## Stream Dimensions
| Property | Value |
| --------------------- | ------- |
| Width | 1024 px |
| Height | 600 px |
| Format | H.264 |
| Browser chrome height | 155 px |
Always read dimensions from `session.streaming.dimensions` as these may vary by instance.
***
## Combining Streaming with Control
Video streaming is essential when using manual interaction features. See the [Manual Interaction](/usage-guides/manual-interaction) guide for detailed instructions on combining video with clicks, typing, and keyboard inputs.
### Quick Example
```javascript theme={null}
import { io } from "socket.io-client";
// 1. Create session
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
task: {
prompt: "Go to example.com",
startingUrl: "https://example.com"
}
})
}).then(r => r.json());
// 2. Setup video stream
const video = document.getElementById("stream");
video.src = session.streaming.webViewURL;
// 3. Connect WebSocket
const socket = io("https://api.webrun.ai", {
auth: { sessionId: session.sessionId },
transports: ["websocket"]
});
// 4. Setup click handler with coordinate mapping
const canvas = document.getElementById("clickable-overlay");
canvas.addEventListener("click", (e) => {
const coords = mapCoords(
e.clientX,
e.clientY,
canvas,
session.streaming.dimensions
);
if (coords) {
socket.emit("message", {
actionType: "interaction",
action: { type: "CLICK", x: coords.x, y: coords.y }
});
}
});
function mapCoords(clientX, clientY, canvas, streamDimensions) {
const rect = canvas.getBoundingClientRect();
const SERVER_WIDTH = streamDimensions?.width || 1024;
const SERVER_HEIGHT = streamDimensions?.height || 600;
const Y_OFFSET = 155; // Browser chrome height
// Adjust for canvas position
const x = clientX - rect.left;
const y = clientY - rect.top;
// Map to server coordinates
return {
x: Math.round((x / rect.width) * SERVER_WIDTH),
y: Math.round((y / rect.height) * SERVER_HEIGHT) + Y_OFFSET
};
}
```
***
## Coordinate Mapping for Manual Interaction
When combining video streaming with manual interaction, map click coordinates from your display to server coordinates.
### Understanding the Coordinate System
```
Server Browser (1024 × 755 total)
┌────────────────────────────────────┐
│ Browser Toolbar (155px height) │ ◄─ Not clickable
├────────────────────────────────────┤
│ │
│ Content Area (1024 × 600) │ ◄─ This is what you see in stream
│ │
│ │
└────────────────────────────────────┘
```
The stream shows only the **content area** (1024 × 600), but clicks must account for the browser chrome offset.
### Mapping Function
```javascript theme={null}
function mapCoords(clientX, clientY, canvas, streamDimensions) {
const rect = canvas.getBoundingClientRect();
// Server dimensions
const SERVER_WIDTH = streamDimensions?.width || 1024;
const SERVER_HEIGHT = streamDimensions?.height || 600;
const Y_OFFSET = 155; // Browser chrome height
const SERVER_ASPECT = SERVER_WIDTH / SERVER_HEIGHT;
// Calculate letterboxing (black bars)
const containerAspect = rect.width / rect.height;
let videoWidth, videoHeight, offsetX, offsetY;
if (containerAspect > SERVER_ASPECT) {
// Horizontal black bars
videoHeight = rect.height;
videoWidth = rect.height * SERVER_ASPECT;
offsetX = (rect.width - videoWidth) / 2;
offsetY = 0;
} else {
// Vertical black bars
videoWidth = rect.width;
videoHeight = rect.width / SERVER_ASPECT;
offsetX = 0;
offsetY = (rect.height - videoHeight) / 2;
}
// Adjust for video position
const videoX = clientX - rect.left - offsetX;
const videoY = clientY - rect.top - offsetY;
// Check bounds
if (videoX < 0 || videoX > videoWidth || videoY < 0 || videoY > videoHeight) {
return null; // Click outside video area (black bars)
}
// Map to server coordinates
return {
x: Math.round((videoX / videoWidth) * SERVER_WIDTH),
y: Math.round((videoY / videoHeight) * SERVER_HEIGHT) + Y_OFFSET
};
}
```
### Usage Example
```javascript theme={null}
canvas.onclick = (e) => {
const coords = mapCoords(
e.clientX,
e.clientY,
canvas,
session.streaming.dimensions
);
if (!coords) {
console.log("Clicked outside video area");
return;
}
socket.emit("message", {
actionType: "interaction",
action: { type: "CLICK", x: coords.x, y: coords.y }
});
};
```
***
## Connection States (WebRTC)
Monitor the connection:
```javascript theme={null}
pc.onconnectionstatechange = () => {
console.log("State:", pc.connectionState);
// "connecting" → "connected" → "disconnected"
if (pc.connectionState === "failed") {
console.error("Connection failed, reconnecting...");
pc.close();
connectStream(webRTCURL, videoElement);
}
if (pc.connectionState === "disconnected") {
console.warn("Connection lost, attempting to reconnect...");
}
};
pc.oniceconnectionstatechange = () => {
console.log("ICE State:", pc.iceConnectionState);
};
```
***
## Cleanup
Always close the connection when done:
```javascript theme={null}
function disconnect(pc) {
if (pc) {
pc.close();
pc = null;
}
}
// On session end
socket.on("end_session", () => {
console.log("Session ended");
disconnect(pc);
});
// On page unload
window.addEventListener("beforeunload", () => {
disconnect(pc);
});
```
***
## Troubleshooting
| Issue | Solution |
| ---------------------- | ---------------------------------------------------------- |
| Black screen | Check ICE gathering completed before sending offer |
| No connection | Verify STUN server is reachable, check firewall |
| Choppy video | Network bandwidth issue, reduce other traffic |
| Stream stops | Session may have terminated, check status |
| Audio not playing | Check browser autoplay policies, may need user interaction |
| Clicks not registering | Verify coordinate mapping includes Y\_OFFSET |
### Enable Debug Logging
```javascript theme={null}
pc.addEventListener("icecandidateerror", (e) => {
console.error("ICE candidate error:", e);
});
pc.addEventListener("connectionstatechange", () => {
console.log("Connection state:", pc.connectionState);
});
```
***
## Complete Integration Example
```javascript theme={null}
class WebRunStream {
constructor(sessionId, webRTCURL) {
this.sessionId = sessionId;
this.webRTCURL = webRTCURL;
this.pc = null;
}
async connect(videoElement) {
this.pc = new RTCPeerConnection({
iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
});
this.pc.addTransceiver("video", { direction: "recvonly" });
this.pc.addTransceiver("audio", { direction: "recvonly" });
this.pc.ontrack = (e) => {
if (!videoElement.srcObject) {
videoElement.srcObject = new MediaStream();
}
videoElement.srcObject.addTrack(e.track);
};
this.pc.onconnectionstatechange = () => {
if (this.pc.connectionState === "failed") {
this.reconnect(videoElement);
}
};
const offer = await this.pc.createOffer();
await this.pc.setLocalDescription(offer);
await new Promise((resolve) => {
if (this.pc.iceGatheringState === "complete") resolve();
else this.pc.onicegatheringstatechange = () => {
if (this.pc.iceGatheringState === "complete") resolve();
};
});
const response = await fetch(this.webRTCURL, {
method: "POST",
headers: { "Content-Type": "application/sdp" },
body: this.pc.localDescription.sdp
});
const answer = await response.text();
await this.pc.setRemoteDescription({ type: "answer", sdp: answer });
}
async reconnect(videoElement) {
console.log("Reconnecting...");
this.disconnect();
await new Promise(r => setTimeout(r, 1000));
await this.connect(videoElement);
}
disconnect() {
if (this.pc) {
this.pc.close();
this.pc = null;
}
}
}
// Usage
const stream = new WebRunStream(
session.sessionId,
session.streaming.webRTCURL
);
await stream.connect(document.getElementById("video"));
```
***
Click, type, and control the browser manually
Pause, resume, stop, and terminate tasks
# Webhooks
Source: https://docs.webrun.ai/usage-guides/webhooks
Receive automated notifications when tasks complete
## Overview
Webhooks enable your application to receive real-time notifications when tasks complete. Instead of polling for results, configure a webhook endpoint to receive data automatically when the AI agent finishes its work.
**Use cases:**
* Automated data pipelines that trigger on task completion
* Real-time notifications to downstream systems
* Integration with third-party services and APIs
* Event-driven architectures without polling overhead
***
## Configuration
Add a `webhook` object to your session or task request to enable webhook notifications.
### Webhook Parameters
| Parameter | Type | Required | Description |
| --------------- | -------- | -------- | ------------------------------------------------ |
| `name` | `string` | Yes | Identifier for this webhook (useful for logging) |
| `url` | `string` | Yes | HTTPS endpoint URL to receive the webhook |
| `auth` | `string` | No | Authorization header value sent with the request |
| `submittedData` | `string` | Yes | Specifies what data to include in the payload |
### submittedData Options
| Value | Description | Best For |
| ----------------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `"ai_response"` | The response from the AI (text, structured\_json, or structured\_csv): only the results/output from the LLM | Production data pipelines |
| `"full_response"` | Full body response that includes the usage info | Debugging, audit logging |
| `"just_ping"` | Just a ping notification, no data payload | Triggering external workflows |
***
## Basic Example
```javascript theme={null}
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
mode: "default",
task: {
prompt: "Extract the main headline from the page",
startingUrl: "https://news.ycombinator.com",
webhook: {
name: "HN Headlines",
url: "https://api.yoursite.com/webhooks/headlines",
auth: "Bearer your-secret-token",
submittedData: "full_response"
}
}
})
}).then(r => r.json());
```
***
## With Structured Output
Combine webhooks with [structured output](/usage-guides/structured-output) for validated JSON delivered directly to your endpoint.
```javascript theme={null}
const session = await fetch("https://api.webrun.ai/start/start-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
mode: "default",
task: {
prompt: "Extract product information from the page",
startingUrl: "https://example.com/product",
maxDuration: 300000,
outputType: "structured_json",
outputSchema: {
type: "object",
properties: {
title: { type: "string" },
price: { type: "number" },
inStock: { type: "boolean" },
description: { type: "string" }
},
required: ["title", "price"],
additionalProperties: false
},
webhook: {
name: "Product Webhook",
url: "https://api.mysite.com/products",
auth: "Bearer token123",
submittedData: "ai_response"
}
}
})
}).then(r => r.json());
```
Use `submittedData: "ai_response"` to receive only the AI's output (text, structured\_json, or structured\_csv), reducing payload size and simplifying your webhook handler.
***
## Webhook Payload
The payload sent to your endpoint depends on the `submittedData` setting.
### full\_response Payload
```json theme={null}
{
"type": "task_completed",
"sessionId": "sess_abc123",
"taskId": "task_xyz789",
"data": {
"message": "{\"title\":\"Product Name\",\"price\":29.99}",
"prompt_tokens": 8500,
"completion_tokens": 2300,
"total_tokens": 10800,
"completion_time": 12.5
},
"usage": {
"inputTokens": 8500,
"outputTokens": 2300,
"computeTime": 12.5,
"cost": 0.0124
},
"completedAt": "2024-01-15T10:30:00.000Z"
}
```
### ai\_response Payload
```json theme={null}
{
"title": "Product Name",
"price": 29.99,
"inStock": true,
"description": "A great product"
}
```
### just\_ping Payload
```json theme={null}
{
"event": "task_completed",
"sessionId": "sess_abc123",
"taskId": "task_xyz789",
"completedAt": "2024-01-15T10:30:00.000Z"
}
```
***
## Receiving Webhooks
Your webhook endpoint should:
1. Accept POST requests with JSON body
2. Return a 2xx status code to acknowledge receipt
3. Process the webhook asynchronously if needed
### Example Webhook Handler (Node.js/Express)
```javascript theme={null}
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhooks/products', (req, res) => {
// Verify authorization (recommended)
const authHeader = req.headers['authorization'];
if (authHeader !== 'Bearer your-secret-token') {
return res.status(401).json({ error: 'Unauthorized' });
}
// Process the webhook payload
const productData = req.body;
console.log('Received product data:', productData);
// Store in database, trigger workflows, etc.
saveToDatabase(productData);
// Acknowledge receipt
res.status(200).json({ received: true });
});
app.listen(3000);
```
### Example Webhook Handler (Python/Flask)
```python theme={null}
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/webhooks/products', methods=['POST'])
def receive_webhook():
# Verify authorization (recommended)
auth_header = request.headers.get('Authorization')
if auth_header != 'Bearer your-secret-token':
return jsonify({'error': 'Unauthorized'}), 401
# Process the webhook payload
product_data = request.json
print('Received product data:', product_data)
# Store in database, trigger workflows, etc.
save_to_database(product_data)
# Acknowledge receipt
return jsonify({'received': True}), 200
if __name__ == '__main__':
app.run(port=3000)
```
***
## Security Best Practices
### 1. Use HTTPS
Always use HTTPS endpoints for webhooks to encrypt data in transit.
```json theme={null}
{
"webhook": {
"url": "https://api.yoursite.com/webhooks/data"
}
}
```
### 2. Verify Authorization
Include an `auth` token and verify it in your webhook handler.
```json theme={null}
{
"webhook": {
"auth": "Bearer your-secret-token"
}
}
```
### 3. Validate Payload Structure
Validate incoming data matches your expected schema before processing.
```javascript theme={null}
const { z } = require('zod');
const ProductSchema = z.object({
title: z.string(),
price: z.number(),
inStock: z.boolean().optional()
});
app.post('/webhooks/products', (req, res) => {
try {
const validated = ProductSchema.parse(req.body);
processProduct(validated);
res.status(200).json({ received: true });
} catch (error) {
console.error('Invalid payload:', error);
res.status(400).json({ error: 'Invalid payload' });
}
});
```
### 4. Use Unique Tokens Per Webhook
Generate unique tokens for different webhook endpoints to limit exposure if one is compromised.
***
## Error Handling
If your webhook endpoint fails to respond or returns an error, the webhook delivery will not be retried. Ensure your endpoint is reliable and returns quickly.
Webhook deliveries are not retried on failure. Design your endpoint to be highly available and respond within 30 seconds.
### Recommended Approach
1. Acknowledge receipt immediately with a 200 status
2. Process the data asynchronously
3. Implement your own retry logic if needed
```javascript theme={null}
app.post('/webhooks/products', async (req, res) => {
// Acknowledge immediately
res.status(200).json({ received: true });
// Process asynchronously
try {
await processProductAsync(req.body);
} catch (error) {
console.error('Processing failed:', error);
// Queue for retry in your own system
await queueForRetry(req.body);
}
});
```
***
## Use Cases
### Data Pipeline Automation
Automatically ingest extracted data into your database or data warehouse.
```javascript theme={null}
{
task: {
prompt: "Extract all product listings from the category page",
outputType: "structured",
outputSchema: {
type: "object",
properties: {
products: {
type: "array",
items: {
type: "object",
properties: {
sku: { type: "string" },
name: { type: "string" },
price: { type: "number" }
}
}
}
}
},
webhook: {
name: "Product Ingestion",
url: "https://api.yoursite.com/ingest/products",
auth: "Bearer ingestion-token",
submittedData: "ai_response"
}
}
}
```
### Notification Systems
Trigger alerts or notifications when tasks complete.
```javascript theme={null}
{
task: {
prompt: "Monitor the page for price changes",
webhook: {
name: "Price Alert",
url: "https://api.yoursite.com/alerts/price-change",
auth: "Bearer alert-token",
submittedData: "just_ping"
}
}
}
```
### Third-Party Integrations
Send data directly to external services like Zapier, Make, or n8n.
```javascript theme={null}
{
task: {
prompt: "Extract contact information from the page",
outputType: "structured",
outputSchema: {
type: "object",
properties: {
name: { type: "string" },
email: { type: "string" },
phone: { type: "string" }
}
},
webhook: {
name: "Zapier Integration",
url: "https://hooks.zapier.com/hooks/catch/123456/abcdef",
submittedData: "ai_response"
}
}
}
```
***
Get validated JSON responses with native schema support
Chain tasks for complex data pipelines
Schedule recurring tasks with automatic webhook delivery