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

> ## Agent Instructions
> Agents: start with https://docs.pre.dev/agents.md, which has complete recipes, plan access, polling rules, errors and limits.
> Authenticate with the workspace API key (pdk_…) from Integrations → Built-in, sent as Authorization: Bearer <key>.
> REST API: https://api.pre.dev (OpenAPI: https://docs.pre.dev/api-reference/openapi.json). AI Gateway: https://api.pre.dev/v1, OpenAI-compatible (OpenAPI: https://docs.pre.dev/api-reference/ai-gateway.openapi.json).
> pre.dev MCP server: npx -y @predotdev/mcp setup adds it to every local coding agent with every pre.dev tool plus the user's own Chrome; the hosted server is https://api.pre.dev/mcp. Search these docs over MCP at https://docs.pre.dev/mcp.

# Stream an existing run

> Attach to an existing browser run with an initial snapshot, live SSE updates, and terminal status.

Submit with `async: true`, save the run ID, then attach to this endpoint. This lets your application recover results even if the stream disconnects.

```bash theme={null}
curl --fail-with-body -N "https://api.pre.dev/browser-agent/$BATCH_ID/stream" \
  -H "Authorization: Bearer $PREDEV_API_KEY"
```

## Event contract

| Event | Payload | When |
| - | - | - |
| `snapshot` | Full run result with available timelines | On connection |
| `batch_meta` | `{ name, taskNames }` | Display names become available |
| `task_event` | `{ taskIndex, type, timestamp, iteration?, data }` | A task emits an event |
| `task_result` | `{ taskIndex, ...taskResult }` | A task finishes |
| `done` | `{ status: "completed" }` or `{ status: "failed" }` | The batch reaches a terminal state |
| `error` | `{ error }` | The stream cannot continue |

The existing-run stream's **`done` contains status only**. Fetch [the run](https://predev.mintlify.site/browser-agents/api/task-status.md) after `done` for final data and credit usage. This differs from the [submission stream](https://predev.mintlify.site/browser-agents/api/run-task.md#streaming), whose `done` contains the full batch.

## Reconnect and recover

An already-terminal run emits `snapshot`, then `done`, then closes. Keepalive lines start with `:` and are not JSON events. Closing the stream does not cancel the run.

The stream has no event-ID replay contract. After a disconnect, fetch a fresh result or reconnect for a new snapshot; do not assume that every transient event will be replayed. Treat EOF without `done` as an interrupted stream and check status.

## Read the stream in code

Send the key in a header, as on every other endpoint, and read the response body as it arrives. The browser's `EventSource` cannot set headers, so use `fetch` or an HTTP client that streams.

```typescript Node.js theme={null}
const response = await fetch(`https://api.pre.dev/browser-agent/${batchId}/stream`, {
  headers: { Authorization: `Bearer ${process.env.PREDEV_API_KEY}` },
});
if (!response.ok || !response.body) throw new Error(`Stream failed: HTTP ${response.status}`);

const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = '';
let finished = false;
while (!finished) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += value;
  let boundary;
  while (!finished && (boundary = buffer.indexOf('\n\n')) !== -1) {
    const frame = buffer.slice(0, boundary);
    buffer = buffer.slice(boundary + 2);
    const event = frame.match(/^event: (.+)$/m)?.[1];
    const data = frame.match(/^data: (.*)$/m)?.[1];
    if (!event || data === undefined) continue; // keepalive comment
    if (event === 'error') throw new Error(JSON.parse(data).error);
    if (event === 'done') finished = true;
    console.log(event, JSON.parse(data));
  }
}
// After done (or an interrupted stream), fetch GET /browser-agent/{id} for the final result.
```

```python Python theme={null}
import json
import os
import requests

with requests.get(
    f"https://api.pre.dev/browser-agent/{batch_id}/stream",
    headers={"Authorization": f"Bearer {os.environ['PREDEV_API_KEY']}"},
    stream=True,
    timeout=(10, 120),
) as response:
    response.raise_for_status()
    event = None
    for line in response.iter_lines(decode_unicode=True):
        if line.startswith("event: "):
            event = line[len("event: "):]
        elif line.startswith("data: ") and event:
            data = json.loads(line[len("data: "):])
            if event == "error":
                raise RuntimeError(data.get("error"))
            print(event, data)
            if event == "done":
                break
# After done (or an interrupted stream), fetch GET /browser-agent/{id} for the final result.
```

The SDKs stream **submission** responses; use direct HTTP for this existing-run endpoint.

## Errors

These statuses arrive before streaming begins. Once headers are sent, handle SSE `error` frames as failures even with HTTP `200`.

| Status | When |
| - | - |
| `400` | `id` is not a valid run ID |
| `401` | Missing or invalid key |
| `404` | No run with this ID in your account |
| `503` | Streaming capacity is full; poll [`GET /browser-agent/{id}`](https://predev.mintlify.site/browser-agents/api/task-status) instead |

Each status has an example body in the response examples. See [errors and retries](https://predev.mintlify.site/api-reference/errors.md).


## OpenAPI

````yaml api-reference/openapi.json GET /browser-agent/{id}/stream
openapi: 3.1.0
info:
  title: pre.dev API
  description: >-
    Public REST API for software specifications, browser automation, and credit
    balance. Base URL: https://api.pre.dev. MCP is documented separately at
    https://docs.pre.dev/mcp/tools.
  version: 1.1.0
  contact:
    name: pre.dev Support
    url: https://pre.dev
    email: support@pre.dev
  license:
    name: Proprietary
    url: https://pre.dev/terms
servers:
  - url: https://api.pre.dev
    description: Production API Server
security:
  - apiKeyAuth: []
  - xApiKey: []
tags:
  - name: Specifications
  - name: Browser Agents
  - name: Account
paths:
  /browser-agent/{id}/stream:
    get:
      tags:
        - Browser Agents
      summary: Watch an existing browser run
      description: >-
        SSE: snapshot, batch_meta, task_event, task_result, done, error. The
        done payload is status only, unlike POST streaming. Already finished
        runs emit snapshot then done. No replay cursor; reconnect for a fresh
        snapshot, or poll after interruption.
      operationId: streamBrowserAgent
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            description: 24-character record ID.
            pattern: ^[a-fA-F0-9]{24}$
      responses:
        '200':
          description: >-
            SSE stream. Errors after headers arrive as error events, not new
            HTTP status codes.
          content:
            text/event-stream:
              schema:
                type: string
              example: >+
                event: snapshot

                data:
                {"id":"64b7f3e1c2a9d5e6f8a01234","status":"processing","total":1,"completed":1,"results":[{"status":"PENDING"}]}


                event: batch_meta

                data: {"name":"Example lookup","taskNames":["Read title"]}


                event: task_result

                data: {"taskIndex":0,"status":"SUCCESS","data":{"title":"Example
                Domain"},"creditsUsed":0.1}


                event: done

                data: {"status":"completed"}

        '400':
          description: Invalid request.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error: invalid batch id
        '401':
          description: Missing, invalid, or ineligible authentication.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                missing_key:
                  summary: No key sent
                  value:
                    error: Missing API key
                    message: >-
                      Please provide an API key via Authorization: Bearer
                      <token> header or x-api-key header
                invalid_key:
                  summary: Unknown key
                  value:
                    error: Authentication failed
                    message: Invalid API key
        '404':
          description: Record unavailable.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error: batch not found
        '503':
          description: Streaming capacity unavailable; retry later or use polling.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error: >-
                  SSE capacity exceeded on this pod (5000/5000). Fall back to
                  polling GET /browser-agent/:id.
      security:
        - apiKeyAuth: []
        - xApiKey: []
components:
  schemas:
    Error:
      type: object
      required:
        - error
      properties:
        error:
          type: string
        message:
          type: string
          description: Optional detail; not returned by every endpoint.
        code:
          type: string
          description: Machine-readable code when available.
        actionUrl:
          type: string
          format: uri
        requiresSubscription:
          type: boolean
        trialsUsed:
          type: integer
        maxTrials:
          type: integer
      additionalProperties: true
  securitySchemes:
    apiKeyAuth:
      type: http
      scheme: bearer
      bearerFormat: API key
      description: >-
        Your pre.dev workspace API key (pdk_...) from Integrations, Built-in
        tab: https://pre.dev/projects/integrations?tab=built-in
    xApiKey:
      type: apiKey
      in: header
      name: x-api-key
      description: 'Alternative to Authorization: Bearer.'

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.