term

A client for gateway-hosted terminals: REST lifecycle plus one websocket attachment

JupyAsyncTerminalClient connects to terminals hosted by 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 for terminal lifecycle requests at /api/terminals and a websocket for input, output and terminal controls.

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.

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

JupyAsyncTerminalClient

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.

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
{'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:

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

JupyAsyncTerminalClient.aclose

async def aclose():

source

JupyAsyncTerminalClient.frames

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

JupyAsyncTerminalClient.resize

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

source

JupyAsyncTerminalClient.write

async def write(
    data:str
):

source

JupyAsyncTerminalClient.connect

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.

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:]
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.

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
(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.

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
{'type': 'eof', 'code': -1}