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

# WebSocket Attach

> Stream an exec's output with resumable byte offsets, write to its stdin, and write to the sandbox main process's stdin over WebSockets.

Two WebSocket endpoints carry interactive I/O:

| Endpoint | Carries |
| - | - |
| `wss://api.telnyx.com/v2/ai/sandboxes/{sandbox_id}/execs/{exec_id}/attach?offset=0` | An exec's stdout and stderr, replayed from a byte offset then live, and its stdin. |
| `wss://api.telnyx.com/v2/ai/sandboxes/{sandbox_id}/attach` | The main process's stdin only. Its output comes through [logs](https://developers.telnyx.com/docs/gpu-sandboxes/logs.md). |

> [!TIP]
>
> The CLI's `exec` and `execs attach` commands implement this protocol, resuming included. Use this page to build a client of your own.

## Connect

Send the API key in the handshake's `Authorization: Bearer` header. Browsers can't set that header on a WebSocket, so connect from a server-side client.

The handshake is an HTTP request. A refusal is an HTTP response with the standard Telnyx [error body](https://developers.telnyx.com/docs/gpu-sandboxes/errors.md), never an opened-then-closed socket:

| Status | Error |
| - | - |
| `401` | Missing or invalid API key. |
| `403` | `sandboxes_require_verification`, `sandboxes_not_whitelisted`, or, for an exec attach, `sandboxes_disabled`. |
| `404` | The sandbox or exec doesn't exist, or belongs to another account. |
| `409` | `sandbox_not_running`. |
| `422` | `offset_out_of_range`: `offset` is past the end of the exec's output so far. |
| `429` | `too_many_attaches`: the sandbox already has the maximum number of open attach connections. Close one, or retry later. |
| `503` | A dependency can't answer right now. Retry later. |

Every message after the upgrade is a JSON text frame with a `type` field. Binary data is base64-encoded.

## Exec Attach

The server replays the exec's combined output (stdout and stderr in the order written) from byte `offset`, then streams it live.

### Client Messages

| `type` | Fields | Effect |
| - | - | - |
| `stdin` | `data`: base64, at most 64 KiB decoded | Writes bytes to the exec's stdin. Messages are delivered whole and in order; the server takes the next one only after the process accepted this one. |
| `stdin_eof` | — | Closes the exec's stdin (EOF). |

### Server Messages

| `type` | Fields | Meaning |
| - | - | - |
| `output` | `stream` (`stdout` or `stderr`), `offset`, `data` (base64) | A chunk of output. `offset` is the byte offset of `data` in the combined output. |
| `truncated` | `oldest_offset` | The requested offset is older than the retained output, or the reader fell behind it. Replay continues at `oldest_offset`. |
| `gap` | `offset`, `length` | Output in this range was lost and can't be replayed. Offsets still advance past it. |
| `stdin_closed` | — | A `stdin` message arrived after stdin was closed and wasn't delivered. |
| `exit` | `status`, `exit_code`, `reason` | The exec ended. The server then closes the connection with `1000`. |
| `error` | `error` (a Telnyx error object) | Something went wrong. The server then closes the connection. |
| `heartbeat` | — | Keeps the connection alive. Sent every 30 s, and every second while stdin is held back by a process that isn't reading it. Ignore it. |

### Resume

Reconnect at any time, from anywhere, with `offset` set to:

* after an `output` message: its `offset` plus the decoded length of its `data`;
* after a `gap`: its `offset` plus its `length`;
* after a `truncated`: its `oldest_offset`.

Reconnecting this way also covers the edge proxy's connection limit of about 600 seconds. Each exec keeps at least its last 64 MiB of output, within the sandbox's total for exec output (1/16 of its memory, at most 256 MiB), oldest output deleted first. `offset=0` replays everything still retained.

Disconnecting never sends EOF and never stops the process. Use `stdin_eof`, [`POST …/execs/{exec_id}/stdin/close`](https://developers.telnyx.com/docs/gpu-sandboxes/execs#output-and-stdin), or [`POST …/kill`](https://developers.telnyx.com/docs/gpu-sandboxes/execs#send-a-signal).

### Example: Follow an Exec's Output

The following Python client (using the [`websockets`](https://pypi.org/project/websockets/) package, version 14 or later) prints an exec's output and resumes after a dropped connection:

```python theme={null}
import asyncio
import base64
import json
import os
import sys

import websockets

API = "wss://api.telnyx.com/v2/ai"


async def follow(sandbox_id: str, exec_id: str) -> None:
    headers = {"Authorization": f"Bearer {os.environ['TELNYX_API_KEY']}"}
    offset = 0
    while True:
        url = f"{API}/sandboxes/{sandbox_id}/execs/{exec_id}/attach?offset={offset}"
        try:
            async with websockets.connect(url, additional_headers=headers) as ws:
                async for raw in ws:
                    message = json.loads(raw)
                    kind = message["type"]
                    if kind == "output":
                        data = base64.b64decode(message["data"])
                        out = sys.stdout if message["stream"] == "stdout" else sys.stderr
                        out.buffer.write(data)
                        out.flush()
                        offset = message["offset"] + len(data)
                    elif kind == "gap":
                        offset = message["offset"] + message["length"]
                    elif kind == "truncated":
                        offset = message["oldest_offset"]
                    elif kind == "exit":
                        print(f"\n{message['status']}: exit_code={message['exit_code']}", file=sys.stderr)
                        return
                    elif kind == "error":
                        raise RuntimeError(message["error"])
        except websockets.ConnectionClosedError:
            pass  # Cut connection or server restart: resume from `offset`.
        await asyncio.sleep(1)


asyncio.run(follow(sys.argv[1], sys.argv[2]))
```

A refused handshake raises `websockets.InvalidStatus`, which this client doesn't retry.

The client stops at the first `exit` message. An exec that ends `failed` with reason `agent_unavailable` or `cancelled` can still start afterwards (see [Statuses](https://developers.telnyx.com/docs/gpu-sandboxes/execs.md#statuses)), so before treating one of those as final, read the exec again with `GET /v2/ai/sandboxes/{sandbox_id}/execs/{exec_id}`.

### Example: Write to an Exec's Stdin

Start the exec with a command that reads stdin, then send input and EOF:

```python theme={null}
await ws.send(json.dumps({"type": "stdin", "data": base64.b64encode(b"hello\n").decode()}))
await ws.send(json.dumps({"type": "stdin_eof"}))
```

## Main Process Stdin

`wss://api.telnyx.com/v2/ai/sandboxes/{sandbox_id}/attach` writes to the stdin of the sandbox's main process. It accepts the same client messages as the exec attach: `stdin` (at most 64 KiB decoded each) and `stdin_eof`.

The server sends:

| `type` | Fields | Meaning |
| - | - | - |
| `exit` | `exit_code` | The main process ended. The server then closes the connection with `1000`. This `exit_code` is for display; the sandbox's own `exit_code` is authoritative. |
| `stdin_closed` | — | A `stdin` message arrived after stdin was closed and wasn't delivered. |
| `error` | `error` | Something went wrong. The server then closes the connection. |
| `heartbeat` | — | Sent every 30 s. Ignore it. |

Reconnect at any time. Disconnecting never sends EOF, so the process keeps waiting for input. `POST /v2/ai/sandboxes/{sandbox_id}/stdin/close` closes the main process's stdin without a WebSocket.

## Close Codes

| Code | Meaning | Action |
| - | - | - |
| `1000` | The process ended, after `exit`. | Done. |
| `1008` | The client sent an invalid message. An `error` message precedes it. | Fix the message. |
| `1009` | A message was over 128 KiB. | Send smaller `stdin` messages. |
| `1011` | Another server error. | Reconnect and resume. |
| `1012` | The server is restarting. | Reconnect and resume. |
