---
title: core
description: An async Jupyter kernel client over HTTP and websockets
---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

Jupyasyncclient controls kernels through the Jupyter kernels HTTP API and exchanges their messages over a websocket. It works with [rustygate](https://github.com/AnswerDotAI/rustygate), jupygate, and jupyter\_server. HTTP handles kernel creation, interrupt, restart, and deletion. One websocket carries the legacy Jupyter message protocol, with a `channel` field identifying each message's channel.

There is no zmq client in this package. The gateway handles zmq subscriptions, socket identities, and kernel communication. The client's send loop awaits websocket sends.

If you've used jupyter\_client's `AsyncKernelClient`, names such as `execute`, `kernel_info`, and `wait_for_ready` will look familiar. Choose how to receive an execution's result:

- `execute` queues the request and returns its `msg_id` without waiting for a reply.
- `reply` queues the request and returns an awaitable for its `execute_reply`.
- `run` returns an async generator of that execution's messages. It also accepts a handler for that execution's stdin prompts.

Generated `*_request` methods provide access to protocol requests without a dedicated wrapper. Every inbound message also reaches `on_jmsg` once, in websocket arrival order, after request routing. Each includes its `channel`. The callback can be synchronous or asynchronous. An awaitable return completes before the reader takes the next message. Do not await a reply on the same websocket from the callback. An exception from the callback is logged with its traceback and the receive loop continues. Consumers that prefer queues can attach `JmsgQueues`. We'll use its merged `jmsg` queue below.

The examples start a disposable jupygate server and an [ipymini](https://github.com/AnswerDotAI/ipymini) kernel. The standard protocol operations also work with jupyter\_server. Features such as notebook bindings and kernmini's held executions require the corresponding gateway or kernel extensions.

```python
from fastcore.test import test_eq, test_fail, ExceptionExpected, expect_fail
from fastcore.nbio import msg2out
from jupywire.route import JmsgQueues, OUTPUT_MSGS, COMM_MSGS
from jupywire.ops import EvalError
from pathlib import Path
import ssl
```

## Wire codec

Legacy Jupyter websockets use JSON text frames for messages without buffers. Binary frames contain a count, an offset table, the JSON message, then its raw buffers. The [jupygate docs](https://AnswerDotAI.github.io/jupygate/core.html) describe the byte layout.

`jupywire.session`'s `to_frame` and `from_frame` convert between a message and its frame. Binary decoding returns each buffer as a `memoryview`. This example checks both encodings:

```python
ses = Session(key=b'demo')
msg = ses.msg('comm_msg', dict(comm_id='c', data={}))
msg['channel'] = 'iopub'
test_eq(from_frame(to_frame(msg))['content'], msg['content'])
msg['buffers'] = [b'raw']
back = from_frame(to_frame(msg))
test_eq(bytes(back['buffers'][0]), b'raw')
back['channel']
```

```output
'iopub'
```

## Shared HTTP plumbing

[`KernelApi`](core.md#kernelapi) holds the HTTP plumbing that each client in this package inherits. It joins URL paths and converts `http` to `ws`, or `https` to `wss`, for websocket endpoints. It also prepares token headers and an [AsyncTransport](https://github.com/AnswerDotAI/fasttransport). The transport can use an HTTP client you supply. Otherwise it creates a client for each request.

The `.api` methods come from [fastspec](https://github.com/AnswerDotAI/fastspec). They use a compact, pre-parsed copy of jupygate's public OpenAPI specification in `jg_spec.py`. All operations share the client's transport. Their signatures and documentation come from the specification. Pass `spec`, a fastspec `SpecParser`, to a client to use a different specification, such as rustygate's full one, which also describes its private routes. The `spec` attribute holds the specification in use.

The standard kernel operations work with jupyter\_server too. Rustygate-specific generated operations require an explicit full spec and a Rustygate server.

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

### KernelApi

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

*Shared HTTP plumbing for the Jupyter kernels API: one transport, and the spec-generated ops on `api`.*

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

### build\_spec

```python
def build_spec(
    nm:str='jupyasyncclient/jg_spec.py', url:str='http://localhost:8787', spec=None
):
```

*Write the compact spec module from an OpenAPI dict, or a gateway's `/openapi.json` when omitted.*

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

### jg\_spec

```python
def jg_spec():
```

*The bundled spec of jupygate's public API, loaded once per process from its compact [`jg_spec`](core.md#jg_spec) module.*

## Launching a gateway

[`start_gateway`](core.md#start_gateway) spawns a gateway binary (defaulting to `jupygate`; pass `argv=('rustygate', ...)` for Rustygate) with `--port-file` and `--exit-with-parent`, returning a [`Gateway`](core.md#gateway) once the child binds its listener and writes the bound port. On timeout or failure, the child is killed and reaped. Calling `stop` sends `SIGINT` so the gateway reaps its kernels, falling back to `SIGKILL` after `timeout` seconds.

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

### start\_gateway

```python
def start_gateway(
    argv:tuple=('jupygate',), # Gateway command; e.g. ('rustygate', '--root', root)
    port:int=0, # Port to listen on; 0 lets the OS bind a free one
    token=None, # Auth token passed as --token
    tls:bool=False, # Serve https/wss from a self-signed certificate (--tls)
    timeout:int=10, # Seconds to wait for the gateway to bind and write its port
):
```

*Spawn a gateway binary in the background, returning a [`Gateway`](core.md#gateway) once it binds and reports its port. The gateway shuts itself down when this process exits, however it ends.*

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

### Gateway

```python
def Gateway(
    proc, url
):
```

*A background gateway process and its base URL.*

## The client

[`JupyAsyncKernelClient`](core.md#jupyasynckernelclient) manages one kernel's HTTP operations, websocket, and protocol messages. You can make HTTP calls before opening its websocket. Constructing the client does not create a kernel or open channels.

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

### JupyAsyncKernelClient

```python
def JupyAsyncKernelClient(
    base_url, kernel_id=None, token=None, session_id=None, username=None, headers=None, timeout:int=30,
    http_client=None, reconnect:bool=True, reconnect_ceiling:float=300.0, verify:bool=True, max_size:int=268435456,
    spec=None, default_timeout=None, refresh_headers=None
):
```

*AsyncKernelClient-ish API over the kernels HTTP API plus its websocket channels.*

`aclose` stops the client's background tasks, closes its websocket, and fails pending replies and runs. It leaves the kernel running. `stop_channels` schedules this cleanup without awaiting it. That method still requires a running event loop.

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

### JupyAsyncKernelClient.stop\_channels

```python
def stop_channels():
```

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

### JupyAsyncKernelClient.aclose

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

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

### JupyAsyncKernelClient.start\_kernel

```python
async def start_kernel(
    kernel_name=None, *, headers_=None, **kwargs
):
```

`start_kernel` posts to `/api/kernels`, stores the returned kernel id, and returns the model. It converts non-`None` `path` and `cwd` arguments to strings before sending them. `None` remains unchanged. A 201 response sets `owned=True`; a 200 response reuses an existing kernel and sets `owned=False`. With rustygate, `path` selects the shared kernel for that notebook. Let's start a local gateway and create a kernel:

`headers_` on `start_kernel` and `restart_kernel` applies to that HTTP request. It does not change the client's default headers or websocket handshake.

```python
g = start_gateway()
base_url = g.url
g
```

```output
<Gateway http://127.0.0.1:60485 pid=47780 up>
```

```python
kc = JupyAsyncKernelClient(base_url)
model = await kc.start_kernel()
model
```

```python
{ 'connections': 0,
  'execution_state': 'alive',
  'id': '835147e537bb42e990b74a75a4bf9d1e',
  'language': 'python',
  'last_heartbeat': None,
  'name': '',
  'path': None,
  'pid': 47784}
```

`shutdown_kernel`, `interrupt_kernel`, and `restart_kernel` call the corresponding HTTP endpoints. They do not require open websocket channels. `shutdown_kernel` also closes this client, even if the HTTP deletion fails.

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

### JupyAsyncKernelClient.restart\_kernel

```python
async def restart_kernel(
    *, headers_=None
):
```

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

### JupyAsyncKernelClient.interrupt\_kernel

```python
async def interrupt_kernel():
```

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

### JupyAsyncKernelClient.shutdown\_kernel

```python
async def shutdown_kernel():
```

*Request kernel deletion, then close this client even if deletion fails.*

`model` returns the gateway's kernel model. Rustygate includes `execution_state`, `pid`, and the bound notebook `path`; other servers can return different fields.

`is_alive` reports whether the kernel is available. It returns `False` without a kernel id, for a dead kernel, or when it cannot fetch the model. Unknown ids produce HTTP 404. Busy, idle, and unresponsive kernels count as alive. A nonempty model without `execution_state` also counts as alive, for compatibility with other servers.

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

### JupyAsyncKernelClient.is\_alive

```python
async def is_alive():
```

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

### JupyAsyncKernelClient.model

```python
async def model():
```

*What the gateway reports about this kernel (jupyter's `kernel model`): `execution_state`, `pid`, `path`, ...*

```python
m = await kc.model()
test_eq((m['id'], await kc.is_alive()), (kc.kernel_id, True))
none_kc = JupyAsyncKernelClient(base_url)
test_eq(await none_kc.is_alive(), False)
m
```

```python
{ 'connections': 0,
  'execution_state': 'alive',
  'id': '835147e537bb42e990b74a75a4bf9d1e',
  'language': 'python',
  'last_heartbeat': 1789266815.870322,
  'name': '',
  'path': None,
  'pid': 47784}
```

Use `.api` for operations without a convenience method. Displaying an operation shows the signature and parameter documentation from the bundled specification:

```python
test_eq((await kc.api.kernels.get_kernel(kid=kc.kernel_id))['id'], kc.kernel_id)
kc.api.kernels.restart
```

`await kernels.restart(kid)`

Restart the kernel in place, keeping its id and its clients' websockets; returns the new model.

Parameters:

- kid (str, required): Kernel id

Call options (in addition to schema parameters): `headers_` adds HTTP headers; `query_` merges extra query entries; `body_` merges extra body fields; `raw_=True` returns the transport response without decoding it.

`stream=True` returns an async iterator after awaiting the call. It cannot be combined with `raw_=True`.

HTTP errors raise [`fasttransport.errors.APIError`](https://AnswerDotAI.github.io/fasttransport/errors.html#apierror); inspect its `status_code` and message.

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

### KernelApi.kernel\_for

```python
async def kernel_for(
    path
):
```

*The non-dead kernel model bound to notebook `path`, or None*

`kernel_for(path)` asks rustygate for kernels bound to that notebook path and returns the first model whose `execution_state` is not `dead`. It returns `None` when none match. A dead kernel can retain its binding in the registry without counting as a live match.

This method belongs to [`KernelApi`](core.md#kernelapi) and calls the list endpoint. It does not depend on the calling client's `kernel_id`. On stock Jupyter servers and `jupygate`, direct `/api/kernels` creates are independent; use [`JupyAsyncSessionsClient`](sessions.md#jupyasyncsessionsclient) over `/api/sessions` for path-to-kernel bindings.

```python
b1,b2 = JupyAsyncKernelClient(base_url),JupyAsyncKernelClient(base_url)
await b1.start_kernel(path='same.ipynb')
await b2.start_kernel(path='same.ipynb')
assert b1.kernel_id != b2.kernel_id
await b1.shutdown_kernel()
await b2.shutdown_kernel()
```

### How it works

`jupywire.route.RouterOps` handles messages for both this client and `conkernelclient`. Jupywire's `DESIGN.md` explains the shared routing contract.

The receive loop passes each decoded message to `route`. A run collects messages with its request id in `parent_header.msg_id`. Its stdin prompts are answered by its `on_stdin` handler. A shell or control message can resolve a pending reply with the same parent id. Every message also reaches `on_jmsg` once after this routing. Notification does not transfer stdin ownership.

A `status` with `execution_state='dead'` takes precedence over those routes. It fails pending replies and runs, then reaches `on_jmsg`. The router also remembers stdin request headers for `input` replies.

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

### JupyAsyncKernelClient.send

```python
def send(
    msg, channel:str
):
```

*Queue `msg`, stamped with `channel`, as a websocket frame for `_send_loop`; returns the msg\_id.*

`_start_ws` connects to the kernel's channels endpoint and starts the send and receive tasks. It cancels old tasks before replacing the connection:

`_exec_req` builds the message header and content, then calls `send` to serialize and queue it. It returns the message id. Websocket messages have no HMAC signature; the gateway handles signing when it forwards them over zmq.

Queue order follows call order. The send loop transmits frames later, independently of when callers await their replies.

`__getattr__` creates senders for names ending in `*_request`. Each returns an awaitable for a reply. This makes new request types accessible without adding wrappers here, but it does not check whether the kernel supports a name. Other missing attributes raise `AttributeError`. `RouterOps` implements `reply` and `run` using `execute` and `send`.

### Connecting

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

### JupyAsyncKernelClient.start\_channels

```python
def start_channels(
    shell:bool=True, iopub:bool=True, stdin:bool=True, control:bool=True
):
```

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

### JupyAsyncKernelClient.channels\_running

```python
def channels_running():
```

`start_channels` schedules the websocket connection and returns the client immediately, including when no connection needs to be started. It supplies `session_id` and, when configured, `token` as query parameters. `channels_running` reports whether the websocket is open. Await `wait_for_ready` before using a newly connected client.

Without an `on_jmsg` callback, the client retains no traffic beyond active request routing. Attach `JmsgQueues` to observe all inbound traffic through queues. It installs itself as the callback and routes messages according to their channel. A timed-out read raises `queue.Empty`.

The examples merge iopub, stdin, and `cells` into one `jmsg` queue. Rustygate uses the nonstandard `cells` channel for notebook change broadcasts named `cell_ops`. The files notebook demonstrates those messages.

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

### JupyAsyncKernelClient.wait\_for\_ready

```python
async def wait_for_ready(
    timeout=None
):
```

`wait_for_ready` opens the channels if needed and awaits one `kernel_info_request` reply. It returns the client when ready. The gateway handles its own zmq subscription readiness. The client does not drain iopub while waiting.

That matters on reconnection: draining could throw away output the gateway replays for this `session_id`. Replayed output and the readiness request's status messages follow the normal routes. An `on_jmsg` handler must tolerate message types it doesn't use.

This method calls the generated request sender, without depending on the `kernel_info` wrapper defined below.

```python
assert kc.start_channels(shell=False, iopub=False, stdin=False, control=False) is kc
assert kc.start_channels().start_channels() is kc
assert await kc.wait_for_ready(timeout=60) is kc
kc.channels_running
```

```output
True
```

You can await a generated sender directly. Here is `comm_info_request`; the `comm_info` convenience method appears later:

```python
m = await kc.comm_info_request(timeout=15)
m['msg_type']
```

```output
'comm_info_reply'
```

### The request API

On Rustygate, `execute(cell_id=...)` runs a saved code or prompt cell. The request carries `cell_id` instead of `code`; the gateway reads the saved source and dialog settings. `cell_id` is distinct from execution-attribution metadata.

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

### JupyAsyncKernelClient.execute

```python
def execute(
    code:str='', silent:bool=False, store_history:bool=True, user_expressions=None, allow_stdin=None,
    stop_on_error:bool=True, msg_id=None, metadata=None, subshell_id=None, buffers=None, cell_id=None
):
```

*Queue an `execute_request` without waiting for a reply; return its msg\_id.*

Let's attach `JmsgQueues` for the remaining examples. A fire-and-forget `execute` has no reply waiter or run to collect its messages. Its printed output reaches the merged queue:

```python
qs = JmsgQueues(kc, queues=('shell', 'control', 'jmsg'), merge=dict(iopub='jmsg', stdin='jmsg', cells='jmsg'))
kc.execute("print('unread')")
s = await qs.jmsg_for('stream', timeout=15)
s['content']['text']
```

```output
'unread\n'
```

Awaiting `reply` gives you the `execute_reply`. Its iopub output still arrives separately through `on_jmsg`, which our queue adapter collects:

```python
rep = await kc.reply("print('hello'); 6*7", timeout=30)
test_eq(rep['content']['status'], 'ok')
s = await qs.jmsg_for('stream', timeout=15)
r = await qs.jmsg_for('execute_result', timeout=15)
dict(stream=s['content']['text'].strip(), result=r['content']['data']['text/plain'])
```

```output
{'stream': 'hello', 'result': '42'}
```

Use `pred` to select more than a message type. This reads until it finds an `idle` status. `jmsg_for` discards messages that don't match:

```python
idle = await qs.jmsg_for('status', pred=lambda m: m['content']['execution_state']=='idle', timeout=15)
idle['content']['execution_state']
```

```output
'idle'
```

Several requests can wait for replies at once. Each future matches its own request id. Calls queue requests immediately, before you await their results. Await order does not change submission order:

```python
reps = await asyncio.gather(*[kc.reply(f'{i}*{i}', timeout=30) for i in range(5)])
[r['content']['status'] for r in reps]
```

```output
['ok', 'ok', 'ok', 'ok', 'ok']
```

Pass `msg_id` to `execute`, `reply`, or `run` to choose the request's header id. The kernel copies it into the parent header of messages caused by that request. Hosts use this to associate output with their own work, such as solveit's `{message_id}.{token}` ids. Use distinct ids for requests that are in flight together:

```python
rep = await kc.reply("21*2", timeout=30, msg_id='myid.abc123')
test_eq(rep['parent_header']['msg_id'], 'myid.abc123')
```

A timeout or cancellation removes a pending reply's entry. It does not stop the kernel execution. If the reply arrives later, no waiter claims it and the router passes it to `on_jmsg`:

```python
lid = f'late.{uuid.uuid4().hex[:6]}'
w = kc.reply('import time; time.sleep(1)', timeout=0.25, msg_id=lid)
with ExceptionExpected(TimeoutError): await w
assert lid not in kc.replies
late = await qs.jmsg_for('execute_reply', queue='shell', pred=lambda m: m['parent_header']['msg_id']==lid, timeout=15)
late['msg_type']
```

```output
'execute_reply'
```

These methods send JEP 91 subshell requests on the control channel. Ipymini accepts a stable `subshell_id`: creating it again returns the same subshell. Omitting the id creates a new one. `list_subshell` returns the live ids.

The example starts work in a subshell and requests completion from the main shell while that work continues. These behaviors require kernel support.

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

### JupyAsyncKernelClient.delete\_subshell

```python
def delete_subshell(
    subshell_id:str, timeout=None
):
```

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

### JupyAsyncKernelClient.list\_subshell

```python
def list_subshell(
    timeout=None
):
```

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

### JupyAsyncKernelClient.create\_subshell

```python
def create_subshell(
    subshell_id=None, timeout=None
):
```

```python
sub = (await kc.create_subshell('lesson-sidecar', timeout=15))['content']['subshell_id']
same = (await kc.create_subshell('lesson-sidecar', timeout=15))['content']['subshell_id']
test_eq((sub, same), ('lesson-sidecar', 'lesson-sidecar'))
assert sub in (await kc.list_subshell(timeout=15))['content']['subshell_id']
await kc.complete('imp', timeout=15)  # the first completion is slow, so it runs before the timed one
busy = kc.reply('import time; time.sleep(1.5)', timeout=30, subshell_id=sub)
matches,_ = await kc.complete('imp', timeout=1)
rep = await busy
await kc.delete_subshell(sub, timeout=15)
rep['content']['status'], rep['parent_header']['subshell_id']==sub, 'import' in matches
```

```output
('ok', True, True)
```

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

### JupyAsyncKernelClient.release

```python
def release(
    msg_id:str, status:str='ok', timeout=None
):
```

*Complete a held execute (kernmini's `hold` metadata); `status='error'` makes the hold's reply an error, engaging the kernel's stop-on-error tail abort*

Kernmini's `hold` execute metadata pauses ordinary queued work while another application does work outside the kernel. Requests with numeric `priority` metadata can run ahead of that queue. Higher priorities run first, with FIFO order within one priority.

The gateway forwards this metadata unchanged. `release` sends a control request to finish the hold. Its reply's `found` field says whether that hold still existed. Releasing an expired hold has no effect:

```python
hid = f'hold1.{uuid.uuid4().hex[:6]}'
kc.execute('', metadata=dict(hold=True), msg_id=hid)
tail = kc.reply("'after the hold'", timeout=30)
jump = await kc.reply("'jumped'", timeout=30, metadata=dict(priority=1))
test_eq(jump['content']['status'], 'ok')
rel = await kc.release(hid, timeout=15)
test_eq(rel['content']['found'], True)
test_eq((await tail)['content']['status'], 'ok')
```

Releasing a hold with `status='error'` triggers the kernel's stop-on-error behavior. Queued requests finish with `status='aborted'`, including replies that callers are awaiting.

Shell and control messages use separate zmq channels at the gateway. The example pauses briefly to give the shell request time to queue before the control release arrives:

```python
hid = f'hold2.{uuid.uuid4().hex[:6]}'
kc.execute('', metadata=dict(hold=True), msg_id=hid)
t2 = kc.reply("'never runs'", timeout=30)
await asyncio.sleep(0.2)
await kc.release(hid, status='error', timeout=15)
test_eq((await t2)['content']['status'], 'aborted')
```

`input` answers the latest remembered stdin prompt and copies its header into the reply's `parent_header`:

```python
fut = asyncio.ensure_future(kc.reply("name = input('who? ')", allow_stdin=True, timeout=30))
prompt = await qs.jmsg_for('input_request', timeout=15)
kc.input('Jeremy')
await fut
rep = await kc.reply('name', timeout=30, user_expressions={'v':'name'})
rep['content']['user_expressions']['v']['data']['text/plain']
```

```output
"'Jeremy'"
```

Generated `*_request` methods return full reply messages. For a name held in a variable, use `request(name, ...)`. `shell` and `control` select the channel explicitly.

`RouterOps` also provides conveniences for frontends. `complete` returns completion matches and the replacement start position. `inspect` returns text, or an empty string when nothing matches. Both default the cursor to the end of the code. `check` reports completeness and indentation; `history` returns a history reply. The same methods work in `conkernelclient`. Its comm senders also come from this mixin, but comm messages have no reply.

```python
matches, start = await kc.complete('imp')
assert 'import' in matches
matches[:3]
```

```output
['import']
```

```python
txt = await kc.inspect('print')
assert 'print' in txt
test_eq(await kc.inspect('no_such_name_here'), '')
```

```python
h = await kc.history(timeout=15)
len(h['content']['history']) > 0
```

```output
True
```

`comm_info` and `kernel_info` return the full protocol replies. `check` uses `is_complete_request` to help a frontend decide whether the user has finished typing a cell:

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

### JupyAsyncKernelClient.kernel\_info

```python
def kernel_info(
    timeout=None
):
```

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

### JupyAsyncKernelClient.comm\_info

```python
def comm_info(
    target_name=None, timeout=None
):
```

```python
test_eq(await kc.check('for i in range(3):'), ('incomplete', '    '))
test_eq((await kc.check('1+1'))[0], 'complete')
```

### Calling kernel functions

`eval` calls `func(*args, **kw)` inside the kernel and waits if the result is a coroutine. It retrieves the result through `user_expressions` in an execution reply. The result travels as a repr, not as the original object.

By default, `try_eval` parses that repr when possible. For supported primitive results, it attempts to wrap the value in a class with the kernel-side type's name. A value it cannot reconstruct stays a string. `literal_=False` returns the representation without parsing. `call_=False` treats `func` as an expression instead of calling it.

`ipy` calls methods on `get_ipython()`. Service methods such as `sig_help`, `get_schemas`, and `ranked_complete` call the methods that `ipyfuncs` adds to the shell. This family comes from jupywire's `EvalOps` mixin, shared with `conkernelclient`.

Ordinary `eval` uses the main shell. With `sidecar_=True`, it uses kernmini's persistent subshell named `sidecar`, which the kernel creates on first use. Service methods and variable operations (`xpush`, `get_vars`, `eval_exprs`, and `retr`) default to that serial subshell. The numeric `priority` metadata shown above changes queue order; it does not select the sidecar.

```python
r = await kc.reply('def add(a, b): return a+b')
test_eq(r['content']['status'], 'ok')
test_eq(await kc.eval('add', a=10, b=20), 30)
await kc.reply('a = [1,2,3]')
test_eq(await kc.eval('a', call_=False), [1,2,3])
test_eq(await kc.eval('add', a=30, b=40, literal_=False), '70')
_r = await kc.eval('missing_fn')
assert 'NameError' in _r
```

`eval_expr` evaluates an expression through `user_expressions`. It parses the result with `literal_eval` when possible and otherwise returns the repr string. A kernel error raises `EvalError`. In contrast, `eval` returns error details, usually a traceback, as text:

```python
test_eq(await kc.eval_expr('a[-1] * 2'), 6)
with ExceptionExpected(EvalError, 'NameError'): await kc.eval_expr('no_such_name')
```

Import [ipyfuncs](https://github.com/AnswerDotAI/ipyfuncs) inside the kernel before calling its `_ipy_funcs` services. These examples include that setup:

```python
await kc.reply('import ipyfuncs')
await kc.reply('''def range_ex(
    a:str  # some param
):
    "some func docstring"
    ...''')
sigs = await kc.sig_help(code='range_ex(', line_no=1, col_no=9)
test_eq(sigs[0]['label'], 'range_ex')
schemas = await kc.get_schemas(fs=['range_ex'])
test_eq(schemas['range_ex']['function']['name'], 'range_ex')
```

`xpush`, `retr`, and `eval_exprs` use the serial sidecar by default. `xpush` queues assignments without waiting for a reply. `xenv` also returns without waiting, but sets environment variables through the main shell:

```python
kc.xpush(asdf=4)
test_eq(await kc.retr('asdf'), 4)
test_eq(await kc.eval_exprs(vs=['list(range(5))']), {'list(range(5))': [0,1,2,3,4]})
kc.xenv(hi='jupy')
test_eq(await kc.eval('__os.environ["hi"]', call_=False), 'jupy')
```

### Streaming an execution: `run`

Use `run` when you want one execution's messages as they arrive. A websocket also carries output from other executions, and those messages can arrive between yours. The run collects messages whose parent id matches its request id.

Like `reply`, `run` registers its request and queues it at call time. It returns an async generator of that execution's outputs, statuses, and `execute_reply`. The generator finishes after both the reply and the matching `idle` status arrive. It does not yield stdin requests: those go to the run's `on_stdin` handler. Without that handler, the execution disables stdin.

`exec_outs` collects a run's output messages into a list of nbformat outputs using `msg2out`. `RouterOps` provides both methods. Concurrent runs collect their own traffic. A dead-kernel status makes all waiting runs raise `DeadKernelError`.

Here is the same execution as a message stream and as a list of notebook outputs:

```python
types = [m['msg_type'] async for m in kc.run("print('hi'); 6*7")]
test_eq([t for t in types if t in OUTPUT_MSGS], ['stream', 'execute_result'])
outs = await kc.exec_outs("print('hi'); 6*7")
test_eq([o['output_type'] for o in outs], ['stream', 'execute_result'])
outs
```

```output
[{'output_type': 'stream', 'name': 'stdout', 'text': 'hi\n'},
 {'output_type': 'execute_result',
  'metadata': {'__type': 'int'},
  'data': {'text/plain': '42'},
  'execution_count': 20}]
```

Render messages inside the `async for` loop as they arrive. The loop body can await other work, as clikernel's stream worker does.

Close the generator if you stop reading early. Closing removes the run's routing entry; it does not interrupt the cell. The remaining messages then reach `on_jmsg`:

```python
gen = kc.run("print('early'); 6*7")
test_eq((await anext(gen))['msg_type'], 'execute_queued')
await gen.aclose()
test_eq(kc.runs, {})
s = await qs.jmsg_for('stream', timeout=15)
s['content']['text']
```

```output
'early\n'
```

A cell error produces an `error` output and an `execute_reply` with error status. The run yields both, rather than raising the cell's exception in the client:

```python
msgs = [m async for m in kc.run('1/0')]
rep = next(m for m in msgs if m['msg_type'] == 'execute_reply')
test_eq(rep['content']['status'], 'error')
outs = [msg2out(m) for m in msgs if m['msg_type'] in OUTPUT_MSGS]
test_eq(outs[0]['ename'], 'ZeroDivisionError')
```

Pass `on_stdin` to handle prompts for one run. The callback receives the complete `input_request` and returns an answer. It can be synchronous or asynchronous. Jupywire sends an `input_reply` with the correct parent header:

```python
run_prompts = []
async def answer_stdin(msg):
    run_prompts.append(msg)
    return 'jupy'

async for _ in kc.run("nm = input('who? ')", on_stdin=answer_stdin): pass
name = await kc.retr('nm')
test_eq(name, 'jupy')
dict(prompt=run_prompts[0]['content']['prompt'], name=name)
```

```output
{'prompt': 'who? ', 'name': 'jupy'}
```

`run` also collects comm messages parented to its execution. `COMM_MSGS` contains `comm_open`, `comm_msg`, and `comm_close`. These are protocol messages, not notebook outputs.

Comms let kernel code talk to its host application, as ipyai's `%ipyai` magic does. Comm messages also reach `on_jmsg`:

```python
msgs = [m async for m in kc.run("from comm import create_comm\ncm = create_comm('demo', data=dict(x=1))\ncm.send(dict(y=2))")]
comms = [(m['msg_type'], m['content'].get('data')) for m in msgs if m['msg_type'] in COMM_MSGS]
test_eq(comms[0], ('comm_open', dict(x=1)))
test_eq(comms[1], ('comm_msg', dict(y=2)))
test_eq([m for m in msgs if m['msg_type'] in OUTPUT_MSGS], [])
```

This example submits a separate execution before starting a run. Its output must not appear in the run, and its `idle` must not finish the run. The router sends both executions to `on_jmsg`, but each run collects only its own traffic. The same rule applies to another client's output or a host's silent bridge execution:

```python
foreign_id = kc.execute("'FOREIGN'")
outs = await kc.exec_outs("'MINE'")
test_eq(len(outs), 1)
assert 'MINE' in outs[0]['data']['text/plain'] and 'FOREIGN' not in str(outs)
foreign = await qs.jmsg_for('execute_result', pred=lambda m: m['parent_header']['msg_id']==foreign_id, timeout=15)
assert 'FOREIGN' in str(foreign['content'])
```

Each run registers its routing entry before queueing the request. Several runs on one client therefore collect independently. The test limits the combined wait to 30 seconds to catch a routing failure:

```python
outs = await asyncio.wait_for(asyncio.gather(kc.exec_outs('1+1'), kc.exec_outs("print('two')"), kc.exec_outs('3+3')), 30)
test_eq([o[0]['data']['text/plain'] for o in (outs[0], outs[2])], ['2', '6'])
test_eq(outs[1][0]['text'], 'two\n')
```

Submitting runs concurrently does not make the kernel execute their cells concurrently. They enter its queue. With the default `stop_on_error=True`, an error can abort queued executions with status `aborted`. Pass `stop_on_error=False` when you want later cells to run despite an earlier error:

```python
o1, o2, o3 = await asyncio.wait_for(asyncio.gather(*[kc.exec_outs(c, stop_on_error=False) for c in ('y = 6*7', '1/0', 'y')]), 30)
test_eq((o1, o2[0]['ename'], o3[0]['data']['text/plain']), ([], 'ZeroDivisionError', '42'))
reps = await asyncio.gather(*[kc.reply(c, timeout=30) for c in (r'import time; time.sleep(0.1)', '1/0', 'after_error = 42')])
test_eq([r['content']['status'] for r in reps], ['ok', 'error', 'aborted'])
test_eq(await kc.eval_expr(r"'after_error' in globals()"), False)
```

## Protocol details

An execution reply can include payload dictionaries. Their `source` identifies what the frontend should do. Standard sources include `page` for pager content and `set_next_input` for preparing another input cell.

The aimagic nbextension extends `set_next_input` with `ctype` and `offset`. For example:

```py
pm = get_ipython().payload_manager
pm.write_payload(dict(
    source='set_next_input', text='bar',
    ctype='markdown', replace=False, offset=1))
```

You can use a custom source too. The kernel includes it in the reply; the frontend decides how to handle it. Pass `single=False` to keep multiple payloads with the same source:

```python
code = '''payl = dict(source='testing', foo='bar')
pm = get_ipython().payload_manager
pm.write_payload(payl, single=False)
pm.write_payload(dict(source='testing', foo='baz'), single=False)'''
r = await kc.reply(code, timeout=30)
test_eq([p['foo'] for p in r['content']['payload']], ['bar','baz'])
```

Pass `metadata` and `transient` to `display` to include them in a display message. Transient data describes the live display and should not become persistent notebook content:

```python
kc.execute("from IPython.display import display\ndisplay('hi', metadata={'key':'value'}, transient={'foo':'bar'})")
dd = await qs.jmsg_for('display_data', timeout=15)
test_eq(dd['content']['metadata'], {'key':'value'})
test_eq(dd['content']['transient'], {'foo':'bar'})
```

A `display_id` lets the frontend update an earlier display. The kernel sends `update_display_data` with the same id in `transient`. A frontend that tracks display ids replaces the corresponding content instead of appending a new output:

```python
code = '''from IPython.display import display
display('first', display_id='qqww')
display('second', update=True, display_id='qqww')'''
kc.execute(code)
upd = await qs.jmsg_for('update_display_data', timeout=15)
test_eq(upd['content']['transient'], {'display_id':'qqww'})
test_eq(upd['content']['data']['text/plain'], "'second'")
```

Interrupt through `interrupt_request` on control or through the HTTP `interrupt` endpoint. In this example, the running cell stops with a `KeyboardInterrupt` error output:

```python
task = asyncio.ensure_future(kc.exec_outs("import time; time.sleep(10); print('finished')"))
await asyncio.sleep(0.3)
await kc.interrupt_kernel()
outs = await task
test_eq(outs[0]['ename'], 'KeyboardInterrupt')
```

### Reconnecting

When a websocket closes, pending replies and runs fail with `ConnectionError`. Queued and partially sent frames are discarded. The kernel may continue executing them; the client never resubmits them.

Unless closing or `reconnect=False`, the client reconnects with the same `session_id`. New calls after the gap use the new connection. Set `on_reconnect` to a no-argument callback to reload application state after successful redial. It can return an awaitable. Callback errors are logged without retrying the transport.

Set `refresh_headers` to a no-argument callback (sync or async) returning updated headers when a redial fails, for example to rotate an expiring proxy token before the `404` liveness probe runs. After a failed connection attempt, HTTP `404` from the kernel model ends redial with `DeadKernelError`. Other non-retryable HTTP errors propagate as `APIError`. Retryable failures use backoff from 0.1 to 5 seconds, up to `reconnect_ceiling` (default 300 seconds).

Gateway `restarting` and `execution_lost` notifications also fail old waits without declaring kernel death. Only an actual `dead` status calls `on_dead`.

```python
reconnected, gap_deaths = asyncio.Event(), []
kc.on_reconnect, kc.on_dead = reconnected.set, gap_deaths.append
drop_id = kc.new_msg_id()
fut = asyncio.ensure_future(kc.reply(r"import time; time.sleep(1); reconnect_count = globals().get('reconnect_count', 0) + 1", timeout=20, msg_id=drop_id))
await qs.jmsg_for('status', pred=lambda m: m['parent_header'].get('msg_id') == drop_id and m['content']['execution_state'] == 'busy', timeout=15)
kc._ws.transport.abort()
with expect_fail(ConnectionError): await fut
await asyncio.wait_for(reconnected.wait(), 15)
test_eq((await kc.reply('reconnect_count', timeout=15))['content']['status'], 'ok')
test_eq(await kc.retr('reconnect_count'), 1)
test_eq(gap_deaths, [])
kc.channels_running
```

```output
True
```

A second client can restart the kernel while a run is waiting. The old run fails, the existing websocket serves new work, and `on_dead` is not called:

```python
gen = kc.run("import time; time.sleep(1); 'collected'", timeout=30)
await anext(gen)
peer = JupyAsyncKernelClient(base_url, kernel_id=kc.kernel_id)
try: await peer.restart_kernel()
finally: await peer.aclose()
with expect_fail(ConnectionError): msgs = [m async for m in gen]
test_eq((await kc.reply('1+1', timeout=15))['content']['status'], 'ok')
test_eq(gap_deaths, [])
```

Rustygate reports process exit with a generated `status` whose `content.execution_state` is `dead`. The router calls `on_dead(msg)` and fails remaining waits with `DeadKernelError`, then passes the status to `on_jmsg`.

IOPub loss can be detected before process exit. In that order, old waits already failed with `ConnectionError`; `on_dead` still waits for the actual death status. This disposable kernel demonstrates both the failed execution and the death notification:

```python
d = JupyAsyncKernelClient(base_url)
await d.start_kernel()
d.start_channels()
await d.wait_for_ready(timeout=60)
deaths, dead_seen = [], asyncio.Event()
def died(msg): deaths.append(msg); dead_seen.set()
d.on_dead = died
w = d.reply(r'import os, signal; os.kill(os.getpid(), signal.SIGKILL)', timeout=30)
try: await w
except (ConnectionError, DeadKernelError): pass
else: raise AssertionError(r'pending execution survived kernel death')
await asyncio.wait_for(dead_seen.wait(), 15)
test_eq(deaths[0]['content']['execution_state'], 'dead')
test_eq((await d.model())['execution_state'], 'dead')
test_eq(await d.is_alive(), False)
await d.aclose()
```

`max_size` limits incoming websocket messages to 256 MiB by default. Pass `None` to disable the limit. The websocket library closes the connection when an incoming message exceeds it.

### Closing down

`shutdown` sends a `shutdown_request` on the control channel. `shutdown_kernel` uses HTTP `DELETE` instead, asking the gateway to terminate and remove the process. It also closes this client.

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

### JupyAsyncKernelClient.shutdown

```python
def shutdown(
    restart:bool=False, timeout=None
):
```

`aclose` drains queued outbound frames before stopping the send loop. It allows up to two seconds for the drain. On a working connection, you can queue a fire-and-forget request and immediately close without discarding that request.

To delete the kernel as well as close the client, call `shutdown_kernel`.

Closing a client leaves the kernel running. Another client can attach to it and use the same namespace; messages missed during the gap are not replayed by Rustygate:

```python
a = JupyAsyncKernelClient(base_url)
await a.start_kernel()
a.start_channels()
await a.wait_for_ready(timeout=60)
await a.reply('retained = 42')
await a.aclose()
```

Attach the replacement client by kernel id and read the value:

```python
b = JupyAsyncKernelClient(base_url, kernel_id=a.kernel_id)
b.start_channels()
await b.wait_for_ready(timeout=60)
outs = await b.exec_outs('retained')
test_eq(outs[0]['data']['text/plain'], '42')
await b.shutdown_kernel()
```

### Connecting in one call

`connect` constructs a client, gets or creates a kernel, opens channels, and waits for readiness. Pass `kernel` to attach to an existing id instead. `default_timeout` sets the client's limit, in seconds, for requests, runs and `JmsgQueues` waits that pass no `timeout`. Extra keyword arguments configure kernel creation, not the client constructor.

Only a new kernel (HTTP 201) sets `owned=True`. With rustygate, `path` reuses an existing notebook kernel (HTTP 200) without claiming ownership. When used as an async context manager, the client requests deletion of an owned kernel on exit. An attached client closes its connection without deleting the kernel. Calling `aclose` directly also leaves the kernel running. Use `shutdown_kernel` when you explicitly want to delete it.

A failed or cancelled connection performs the same ownership-aware cleanup before re-raising the error.

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

### JupyAsyncKernelClient.\_\_aexit\_\_

```python
async def __aexit__(
    *exc
):
```

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

### JupyAsyncKernelClient.\_\_aenter\_\_

```python
async def __aenter__():
```

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

### JupyAsyncKernelClient.connect

```python
async def connect(
    base_url, kernel=None, token=None, timeout:int=60, verify:bool=True, default_timeout=None, headers=None,
    refresh_headers=None, **kwargs
):
```

*Return a ready client; only a newly created kernel is owned.*

```python
async with await JupyAsyncKernelClient.connect(base_url, cwd=Path('.')) as k2:
    kid2 = k2.kernel_id
    assert k2.owned and k2.channels_running
    async with await JupyAsyncKernelClient.connect(base_url, kernel=kid2) as att:
        test_eq((att.kernel_id, att.owned), (kid2, False))
    test_eq(await k2.is_alive(), True)
assert not await JupyAsyncKernelClient(base_url, kernel_id=kid2).is_alive()

before = {m['id'] for m in await kc.api.kernels.list_kernels()}
with expect_fail(TimeoutError):
    await JupyAsyncKernelClient.connect(base_url, timeout=0)
test_eq({m['id'] for m in await kc.api.kernels.list_kernels()}, before)
```

With `kernel` set to an existing id, `owned` stays `False`. Leaving this block closes the attached client and leaves the kernel running:

```python
async with await JupyAsyncKernelClient.connect(base_url, kernel=kc.kernel_id) as att: assert not att.owned
test_eq(await kc.is_alive(), True)
```

### TLS

With an `https` address, the HTTP transport and the websocket both check the server's certificate. The default `verify=True` checks it against the certificate authorities your system trusts.

Rustygate's `--tls` option serves HTTPS and WSS using a self-signed certificate it generates at startup. The default check rejects that certificate. For this disposable local test, `verify=False` disables certificate checks for both the HTTP transport and the websocket.

Disabling verification also disables server identity checks. Don't use it as a substitute for trusted certificates on an untrusted network. Token authentication still works with TLS.

```python
gs = start_gateway(tls=True)
assert gs.url.startswith('https://')
async with await JupyAsyncKernelClient.connect(gs.url, verify=False) as ks: rep = await ks.reply('6*7', timeout=30)
test_eq(rep['content']['status'], 'ok')
```

To keep verification on for a certificate your system doesn't trust, pass `verify` an `ssl.SSLContext` that trusts it. The HTTP transport and the websocket both use that context. For a private certificate authority, create it with `ssl.create_default_context(cafile=...)`. This local test fetches the gateway's own certificate and trusts it:

```python
u = urlsplit(gs.url)
ctx = ssl.create_default_context(cadata=ssl.get_server_certificate((u.hostname, u.port)))
async with await JupyAsyncKernelClient.connect(gs.url, verify=ctx) as ks: rep = await ks.reply('6*7', timeout=30)
test_eq(rep['content']['status'], 'ok')
gs.stop()
gs
```

```output
<Gateway https://127.0.0.1:52193 pid=9248 exited 0>
```

```python
await kc.shutdown_kernel()
test_eq(kc.channels_running, False)
test_eq(await none_kc.is_alive(), False)
await none_kc.aclose()
```
