# Live sessions

> Keep a signed-in browser open and drive it over an OpenAI-compatible endpoint.

Source: https://usewrit.app/docs/streaming/

A live session keeps a real browser open on a site, already signed in, and waits for your
commands. Each command runs one of the session's handlers, such as "ask a question" or "search",
and returns the result in seconds, without opening a browser or signing in again. Use it for
chat-style sites and for tools you query many times in a row.

## Set up a live session

-

1. **Build the API as a live session**

In Scribe, pick **Create a persistent website session** and describe the site and
what you want to send it. Or record it yourself: in the recorder, set **Run style** to **Live session**. The result is an API whose handlers are the actions you can call,
each with its own inputs and the fields it returns.

-

2. **Choose how it signs in**

If the site needs a login, link a persona in **Sign-in persona**. The session signs
in once when it starts, then reuses that browser for every command. Turn on **Persist login state** to keep cookies between sessions. Writ runs on your own accounts, with your own
credentials and data, on sites you are authorized to use.

-

3. **Start it**

Click **Start session** on the API's page, or start it from code as shown below.
When no browser is free, the session waits in line (**Session queued — waiting for capacity**) and starts as soon as one is.

## Start, call and stop over REST

All live-session routes take a `wt_` key with streaming permissions.

POST `https://api.usewrit.app/api/streaming/sessions/start` wt_ key

```bash
curl -X POST https://api.usewrit.app/api/streaming/sessions/start \
  -H "Authorization: Bearer $WRIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"workflow_id": 42, "target_url": "https://chat.example.com"}'
```

```python
import os, requests

API = "https://api.usewrit.app/api/streaming"
headers = {"Authorization": f"Bearer {os.environ['WRIT_API_KEY']}"}

session = requests.post(
    f"{API}/sessions/start",
    headers=headers,
    json={"workflow_id": 42, "target_url": "https://chat.example.com"},
).json()
key = session["session_key"]
```

```typescript
const API = "https://api.usewrit.app/api/streaming";
const headers = {
  Authorization: `Bearer ${process.env.WRIT_API_KEY}`,
  "Content-Type": "application/json",
};

const session = await fetch(`${API}/sessions/start`, {
  method: "POST",
  headers,
  body: JSON.stringify({ workflow_id: 42, target_url: "https://chat.example.com" }),
}).then((r) => r.json());
const key = session.session_key;
```

```json
{
  "session_key": "7f3c9a1e5b2d4c6f8a9b0c1d2e3f4a5b",
  "status": "starting",
  "workflow_id": 42,
  "target_url": "https://chat.example.com",
  "current_url": null,
  "handlers": [ { "name": "ask", "input_variables": ["question"] } ],
  "max_duration_seconds": 3600,
  "started_at": null,
  "error_message": null
}
```

Body

- `workflow_id` (integer, required): The id of the live session API.
- `target_url` (string, required): The page the browser opens first.
- `max_duration_seconds` (integer): When the session stops on its own. At least 60; never more than your plan allows (1 hour).
- `form_data` (object): Inputs the sign-in steps need, if any. A missing one is refused before the session starts.
- `execution_target` (string): Where the browser runs: auto, cloud or local (your linked Writ Desktop).

The session goes from `queued` or `starting` to `running` once it has
signed in. Handlers can be called only while it is `running`; before that the call answers `409`.

### Call a handler

POST `https://api.usewrit.app/api/streaming/sessions/{session_key}/invoke/{handler}` wt_ key

```bash
# Check the session until "status" is "running"
curl https://api.usewrit.app/api/streaming/sessions/7f3c9a1e5b2d4c6f8a9b0c1d2e3f4a5b \
  -H "Authorization: Bearer $WRIT_API_KEY"

# Then call a handler
curl -X POST https://api.usewrit.app/api/streaming/sessions/7f3c9a1e5b2d4c6f8a9b0c1d2e3f4a5b/invoke/ask \
  -H "Authorization: Bearer $WRIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"data": {"question": "What changed this week?"}, "timeout": 60}'
```

```python
import time

# Wait until the browser is signed in and ready
while True:
    info = requests.get(f"{API}/sessions/{key}", headers=headers).json()
    if info["status"] == "running":
        break
    if info["status"] in ("ended", "failed", "cancelled"):
        raise RuntimeError(info.get("error_message"))
    time.sleep(2)

answer = requests.post(
    f"{API}/sessions/{key}/invoke/ask",
    headers=headers,
    json={"data": {"question": "What changed this week?"}, "timeout": 60},
    timeout=75,
).json()
print(answer["result"])
```

```typescript
// Wait until the browser is signed in and ready
for (;;) {
  const info = await fetch(`${API}/sessions/${key}`, { headers }).then((r) => r.json());
  if (info.status === "running") break;
  if (["ended", "failed", "cancelled"].includes(info.status)) throw new Error(info.error_message);
  await new Promise((r) => setTimeout(r, 2000));
}

const answer = await fetch(`${API}/sessions/${key}/invoke/ask`, {
  method: "POST",
  headers,
  body: JSON.stringify({ data: { question: "What changed this week?" }, timeout: 60 }),
}).then((r) => r.json());
console.log(answer.result);
```

```json
{
  "session_key": "7f3c9a1e5b2d4c6f8a9b0c1d2e3f4a5b",
  "handler": "ask",
  "result": { "reply": "Three new tickets were opened..." }
}
```

`data` holds the handler's inputs. `timeout` is how long to wait for the
answer, from 1 to 120 seconds (30 by default). If the page does not answer in time, you get `504` and the session stays open.

### List, watch and stop sessions

| Route | What it does |
| --- | --- |
| GET /api/streaming/sessions | Your sessions. Filter with ?status=running; limit up to 200. |
| GET /api/streaming/sessions/{session_key} | One session: status, current page, handlers, activity. |
| GET /api/streaming/sessions/{session_key}/events | A Server-Sent Events stream of what the session emits. |
| POST /api/streaming/sessions/{session_key}/end | Stops the session and closes the browser. |

```bash
curl -X POST https://api.usewrit.app/api/streaming/sessions/7f3c9a1e5b2d4c6f8a9b0c1d2e3f4a5b/end \
  -H "Authorization: Bearer $WRIT_API_KEY"
```

> **cost:** A cloud session is billed for the time its browser stays open, so end it when you are done. It also ends by itself at max_duration_seconds.

## Use it as an OpenAI model

A live session can answer like a chat model, so any OpenAI SDK or tool can talk to it. On the API's **Call** tab, turn on **OpenAI-compatible endpoint**, then choose the **Default handler** (the one each chat message runs) and the **Response field** (the field of its result that becomes the reply). Start a session, then point the SDK at the API's
base URL with your `wt_` key.

POST `https://api.usewrit.app/api/streaming/workflows/{id}/v1/chat/completions` wt_ key

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.usewrit.app/api/streaming/workflows/42/v1",
    api_key=os.environ["WRIT_API_KEY"],
    # default_headers={"X-Session-Key": "7f3c9a1e5b2d4c6f8a9b0c1d2e3f4a5b"},  # pin one session
)

reply = client.chat.completions.create(
    model="streaming",  # or the Model name set on the API's Call tab
    messages=[{"role": "user", "content": "What changed this week?"}],
)
print(reply.choices[0].message.content)
```

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.usewrit.app/api/streaming/workflows/42/v1",
  apiKey: process.env.WRIT_API_KEY,
  // defaultHeaders: { "X-Session-Key": "7f3c9a1e5b2d4c6f8a9b0c1d2e3f4a5b" }, // pin one session
});

const reply = await client.chat.completions.create({
  model: "streaming", // or the Model name set on the API's Call tab
  messages: [{ role: "user", content: "What changed this week?" }],
});
console.log(reply.choices[0].message.content);
```

```bash
curl -X POST https://api.usewrit.app/api/streaming/workflows/42/v1/chat/completions \
  -H "Authorization: Bearer $WRIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "streaming", "messages": [{"role": "user", "content": "What changed this week?"}]}'
```

- `/v1/chat/completions` and `/v1/responses` both work, with `stream: true` too. `GET /v1/models` lists the model name.
- With several sessions running, each new conversation goes to the next session in turn, and later messages of that conversation stay on the same session. Send `X-Session-Key` to pick one yourself.
- With no session running, the call answers `404` ("No active sessions. Start a session first.").

## On Writ Desktop

Live sessions also run on Writ Desktop, in a browser on your computer, for free. Each live session
API has one session at a time. Start and stop it with the local routes, and talk to it through
the API's own OpenAI-compatible base URL, `http://127.0.0.1:8131/v1/workflows/{id}/v1`. If no session is running, the first chat message starts one. Turn on the OpenAI surface in the API's **Call** tab first, and use a local `wlk_` key that can run workflows.

```bash
# Start (or reuse) the workflow's live session on this computer
curl -X POST http://127.0.0.1:8131/v1/streaming/sessions/start \
  -H "Authorization: Bearer wlk_..." \
  -H "Content-Type: application/json" \
  -d '{"workflow_id": 7}'

# Talk to it through the workflow's own OpenAI-compatible base URL
curl -X POST http://127.0.0.1:8131/v1/workflows/7/v1/chat/completions \
  -H "Authorization: Bearer wlk_..." \
  -H "Content-Type: application/json" \
  -d '{"messages": [{"role": "user", "content": "What changed this week?"}]}'

# Stop it
curl -X POST http://127.0.0.1:8131/v1/streaming/sessions/stop \
  -H "Authorization: Bearer wlk_..." \
  -H "Content-Type: application/json" \
  -d '{"workflow_id": 7}'
```

More on local keys and routes: [Desktop local API](https://usewrit.app/docs/local-api).

## Costs and limits

- A session on Writ Cloud costs **2 credits per minute** its browser is open. Calling handlers and sending chat messages adds nothing.
- A session on Writ Desktop, or on your own linked machine, is free.
- A session lasts at most 1 hour on every plan. Start a new one to keep going.
- Starting a cloud session needs credits available to pay for it.

| Plan | Live sessions at once |
| --- | --- |
| Free | 1 |
| Starter | 2 |
| Pro | 3 |
| Growth | 5 |
| Scale | 10 |
| Enterprise | 20 |

Opening one more than your plan allows answers `429`. Plans and credits: [Credits and plans](https://usewrit.app/docs/billing-wallet).

## Next

-
- [Record a workflow](https://usewrit.app/docs/workflows): Record the sign-in and the actions a session repeats.
-
- [Sign-ins and secrets](https://usewrit.app/docs/personas): Personas, 2FA codes and the secrets a session uses.
-
- [Call your API](https://usewrit.app/docs/call): One-shot calls for APIs that don't need a browser kept open.
-
- [SDKs](https://usewrit.app/docs/sdks): The SDKs' session helpers start a session and wait until it runs.
