---
title: term
description: 'A client for gateway-hosted terminals: REST lifecycle plus one websocket
  attachment'
---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

[`JupyAsyncTerminalClient`](term.md#jupyasyncterminalclient) connects to terminals hosted by [rustygate](https://github.com/AnswerDotAI/rustygate) or Jupyter Server. An app can use it to provide a shell on the same machine and filesystem as its kernels, including inside a container.

The client uses [`KernelApi`](core.md#kernelapi) for terminal lifecycle requests at `/api/terminals` and a websocket for input, output and terminal controls.

```python
import asyncio, os, time
from fastcore.test import test_eq
from jupyasyncclient import start_gateway
```

## Lifecycle

Pass a gateway URL when constructing the client. To use an existing terminal, also pass its `name`. Authentication, timeout and HTTP options are the same as for [`JupyAsyncKernelClient`](core.md#jupyasynckernelclient).

`start_terminal` creates a terminal and stores its name on the client. It passes the gateway's creation options through unchanged: `argv`, `cwd`, `env`, `appendenv`, `rc`, `rows` and `cols`.

[source](https://github.com/AnswerDotAI/jupyasyncclient/blob/main/jupyasyncclient/term.py#L37)

### JupyAsyncTerminalClient

```python
def JupyAsyncTerminalClient(
    base_url, name=None, token=None, headers=None, timeout:int=30, http_client=None, verify:bool=True, spec=None
):
```

*One gateway terminal: REST lifecycle through the spec ops on `api`, plus one ws attachment.*

Start a gateway and a Bash shell without startup files. A fixed prompt makes the example output predictable.

```python
BASH = ['bash', '--norc', '--noprofile', '-i']
BENV = dict(os.environ, PS1='$ ', TERM='dumb')
g = start_gateway()
tc = JupyAsyncTerminalClient(g.url)
test_eq(await tc.list_terminals(), [])
model = await tc.start_terminal(argv=BASH, env=BENV)
test_eq((await tc.list_terminals())[0]['name'], tc.name)
model
```

```python
{'alive': True, 'last_activity': 1789266815.656605, 'name': '1', 'path': None}
```

## The channel

`connect` opens `/terminals/websocket/{name}` and returns the server's `setup` frame. The gateway then replays available scrollback as `stdout` frames.

The websocket uses terminado's JSON-array protocol. Every frame is a JSON text list whose first element names the message type:

- The server sends `["setup", {...}]` when a client connects.
- `["stdout", text]` carries terminal output text.
- `["gap", bytes]` reports that the client fell behind the server's replay buffer (rustygate/jupygate extension).
- `["disconnect", 1, ...]` reports that the terminal exited (rustygate/jupygate include the exit code as the third element).
- The client sends `["stdin", text]` for input and `["set_size", rows, cols]` to resize the terminal.

`write` sends `stdin` text. `resize` sends `set_size`. `frames` yields each incoming frame as a parsed list. Use one `frames` iterator per connection. Multiple iterators would compete to read the same socket.

`aclose` closes this client's websocket attachment. It does not delete the terminal. Use `shutdown_terminal` to stop the terminal for all clients.

[source](https://github.com/AnswerDotAI/jupyasyncclient/blob/main/jupyasyncclient/term.py#L76)

### JupyAsyncTerminalClient.aclose

```python
async def aclose():
```

[source](https://github.com/AnswerDotAI/jupyasyncclient/blob/main/jupyasyncclient/term.py#L71)

### JupyAsyncTerminalClient.frames

```python
def frames():
```

*Incoming terminado frames as parsed lists (`['stdout', text]`, `['gap', n]`, `['disconnect', ...]`). Ends when the ws closes normally. A broken connection raises `websockets.ConnectionClosedError`.*

[source](https://github.com/AnswerDotAI/jupyasyncclient/blob/main/jupyasyncclient/term.py#L67)

### JupyAsyncTerminalClient.resize

```python
async def resize(
    rows:int, cols:int
):
```

[source](https://github.com/AnswerDotAI/jupyasyncclient/blob/main/jupyasyncclient/term.py#L63)

### JupyAsyncTerminalClient.write

```python
async def write(
    data:str
):
```

[source](https://github.com/AnswerDotAI/jupyasyncclient/blob/main/jupyasyncclient/term.py#L55)

### JupyAsyncTerminalClient.connect

```python
async def connect():
```

*Open `/terminals/websocket/{name}` and return the `setup` frame; replayed scrollback follows as `stdout` frames.*

Send a command and read its output. Frame boundaries depend on timing, so `read_until` accumulates `stdout` text until the expected pattern appears.

```python
async def read_until(fr, pat:str, timeout=10.0)->str:
    "Accumulate `stdout` frames from async iterator `fr` until `pat` appears (other frames are skipped)."
    buf = ''
    end = time.monotonic() + timeout
    while pat not in buf:
        item = await asyncio.wait_for(anext(fr), end - time.monotonic())
        if item[0] == 'stdout': buf += item[1]
    return buf

setup = await tc.connect()
test_eq(setup[0], 'setup')
fr = tc.frames()
await tc.write('echo wired $((6*7))\n')
out = await read_until(fr, 'wired 42')
out[-20:]
```

```output
b'$((6*7))\r\nwired 42\r\n'
```

A second client can connect to the same terminal name and read its scrollback. This lets an app recover earlier output after a restart or browser refresh.

```python
tc2 = JupyAsyncTerminalClient(g.url, name=tc.name)
test_eq((await tc2.connect())[0], 'setup')
fr2 = tc2.frames()
replay = await read_until(fr2, 'wired 42')
'echo wired' in replay, 'wired 42' in replay
```

```output
(True, True)
```

Check the resized terminal with `stty size`. Either client can shut it down by name. All attached clients then receive a `disconnect` frame.

```python
await tc.resize(50, 120)
await tc.write('stty size\n')
assert '50 120' in await read_until(fr, '50 120')
await tc2.shutdown_terminal()
item = await asyncio.wait_for(anext(fr), 10)
while item[0] == 'stdout': item = await asyncio.wait_for(anext(fr), 10)
test_eq(item[0], 'disconnect')
test_eq(await tc.list_terminals(), [])
item
```

```output
{'type': 'eof', 'code': -1}
```
