Interface of a Kernel connection that is managed by a session.

The Kernel object is tied to the lifetime of the Kernel id, which is a unique id for the Kernel session on the server. The Kernel object manages a websocket connection internally, and will auto-restart if the websocket temporarily loses connection. Restarting creates a new Kernel process on the server, but preserves the Kernel id.

The IKernelConnection is notably missing the full IKernel signals. This interface is for situations where a kernel may change, but we want a user to not have to worry about disconnecting and reconnecting signals when a kernel is swapped. The object that maintains an IKernel, but only provides a user with an IKernelConnection should proxy the appropriate IKernel signals for the user with its own signals. The advantage is that when the kernel is changed, the object itself can take care of disconnecting and reconnecting listeners.

interface IKernelConnection {
    anyMessage: ISignal<Kernel.IKernelConnection, IAnyMessageArgs>;
    clientId: string;
    commsOverSubshells?: CommsOverSubshells;
    connectionStatus: Kernel.ConnectionStatus;
    connectionStatusChanged: ISignal<
        Kernel.IKernelConnection,
        Kernel.ConnectionStatus,
    >;
    disposed: ISignal<Kernel.IKernelConnection, void>;
    handleComms: boolean;
    hasPendingInput: boolean;
    id: string;
    info: Promise<KernelMessage.IInfoReply>;
    iopubMessage: ISignal<
        Kernel.IKernelConnection,
        IIOPubMessage<IOPubMessageType>,
    >;
    isDisposed: boolean;
    model: Kernel.IModel;
    name: string;
    pendingInput: ISignal<Kernel.IKernelConnection, boolean>;
    serverSettings: ServerConnection.ISettings;
    spec: Promise<undefined | KernelSpec.ISpecModel>;
    status: Kernel.Status;
    statusChanged: ISignal<Kernel.IKernelConnection, Kernel.Status>;
    subshellId: null | string;
    unhandledMessage: ISignal<
        Kernel.IKernelConnection,
        KernelMessage.IMessage<KernelMessage.MessageType>,
    >;
    username: string;
    get supportsSubshells(): boolean;
    clone(
        options?: Pick<
            Kernel.IKernelConnection.IOptions,
            "username"
            | "clientId"
            | "handleComms",
        >,
    ): Kernel.IKernelConnection;
    createComm(targetName: string, commId?: string): IComm;
    dispose(): void;
    hasComm(commId: string): boolean;
    interrupt(): Promise<void>;
    reconnect(): Promise<void>;
    registerCommTarget(
        targetName: string,
        callback: (
            comm: IComm,
            msg: ICommOpenMsg<"iopub" | "shell">,
        ) => void | PromiseLike<void>,
    ): void;
    registerMessageHook(
        msgId: string,
        hook: (
            msg: IIOPubMessage<IOPubMessageType>,
        ) => boolean | PromiseLike<boolean>,
    ): void;
    removeCommTarget(
        targetName: string,
        callback: (
            comm: IComm,
            msg: ICommOpenMsg<"iopub" | "shell">,
        ) => void | PromiseLike<void>,
    ): void;
    removeInputGuard(): void;
    removeMessageHook(
        msgId: string,
        hook: (
            msg: IIOPubMessage<IOPubMessageType>,
        ) => boolean | PromiseLike<boolean>,
    ): void;
    requestCommInfo(
        content: { target_name?: string },
    ): Promise<ICommInfoReplyMsg>;
    requestComplete(
        content: { code: string; cursor_pos: number },
    ): Promise<ICompleteReplyMsg>;
    requestCreateSubshell(
        content: Record<string, unknown>,
        disposeOnDone?: boolean,
    ): IControlFuture<ICreateSubshellRequestMsg, ICreateSubshellReplyMsg>;
    requestDeleteSubshell(
        content: { subshell_id: string },
        disposeOnDone?: boolean,
    ): IControlFuture<IDeleteSubshellRequestMsg, IDeleteSubshellReplyMsg>;
    requestExecute(
        content: {
            allow_stdin?: boolean;
            code: string;
            silent?: boolean;
            stop_on_error?: boolean;
            store_history?: boolean;
            user_expressions?: JSONObject;
        },
        disposeOnDone?: boolean,
        metadata?: JSONObject,
    ): IShellFuture<IExecuteRequestMsg, IExecuteReplyMsg>;
    requestHistory(
        content:
            | IHistoryRequestRange
            | IHistoryRequestSearch
            | IHistoryRequestTail,
    ): Promise<IHistoryReplyMsg>;
    requestInspect(
        content: { code: string; cursor_pos: number; detail_level: 0 | 1 },
    ): Promise<IInspectReplyMsg>;
    requestIsComplete(content: { code: string }): Promise<IIsCompleteReplyMsg>;
    requestKernelInfo(): Promise<undefined | IInfoReplyMsg>;
    requestListSubshell(
        content: Record<string, unknown>,
        disposeOnDone?: boolean,
    ): IControlFuture<IListSubshellRequestMsg, IListSubshellReplyMsg>;
    restart(): Promise<void>;
    sendControlMessage<T extends ControlMessageType>(
        msg: IControlMessage<T>,
        expectReply?: boolean,
        disposeOnDone?: boolean,
    ): IControlFuture<IControlMessage<T>, IControlMessage<ControlMessageType>>;
    sendInputReply(
        content: ReplyContent<IInputReply>,
        parent_header: IHeader<"input_request">,
    ): void;
    sendShellMessage<T extends ShellMessageType>(
        msg: IShellMessage<T>,
        expectReply?: boolean,
        disposeOnDone?: boolean,
    ): IShellFuture<IShellMessage<T>, IShellMessage<ShellMessageType>>;
    shutdown(): Promise<void>;
}

Hierarchy

Implemented by

Properties

A signal emitted when any kernel message is sent or received.

This signal is emitted before any message handling has happened. The message should be treated as read-only.

clientId: string

The client unique id.

This should be unique for a particular kernel connection object.

commsOverSubshells?: CommsOverSubshells

Whether comm messages should be sent to kernel subshells, if the kernel supports it.

Sending comm messages over subshells allows processing comms whilst processing execute-request on the "main shell". This prevents blocking comm processing. Options are:

  • disabled: not using subshells
  • one subshell per comm-target (default)
  • one subshell per comm (can lead to issues if creating many comms)
connectionStatus: Kernel.ConnectionStatus

The current connection status of the kernel.

connectionStatusChanged: ISignal<
    Kernel.IKernelConnection,
    Kernel.ConnectionStatus,
>

A signal emitted when the kernel connection status changes.

A signal emitted when the object is disposed.

handleComms: boolean

Whether the kernel connection handles comm messages.

The comm message protocol currently has implicit assumptions that only one kernel connection is handling comm messages. This option allows a kernel connection to opt out of handling comms.

See https://github.com/jupyter/jupyter_client/issues/263

hasPendingInput: boolean

Whether the kernel connection has pending input.

This is a guard to avoid deadlock is the user asks input as second time before submitting his first input

id: string

The id of the server-side kernel.

The kernel info

This promise only resolves at startup, and is not refreshed on every restart.

A signal emitted after an iopub kernel message is handled.

isDisposed: boolean

Test whether the object has been disposed.

This property is always safe to access.

model: Kernel.IModel

The kernel model, for convenience.

name: string

The name of the server-side kernel.

pendingInput: ISignal<Kernel.IKernelConnection, boolean>

A signal emitted when a kernel has pending inputs from the user.

serverSettings: ServerConnection.ISettings

The server settings for the kernel.

spec: Promise<undefined | KernelSpec.ISpecModel>

Get the kernel spec.

A promise that resolves with the kernel spec for this kernel.

This may make a server request to retrieve the spec.

status: Kernel.Status

The current status of the kernel.

A signal emitted when the kernel status changes.

subshellId: null | string

The subshell ID, main shell has null.

A signal emitted for unhandled non-iopub kernel messages that claimed to be responses for messages we sent using this kernel object.

username: string

The client username.

Accessors

Methods

  • Dispose of the resources held by the object.

    If the object's dispose method is called more than once, all calls made after the first will be a no-op.

    It is undefined behavior to use any functionality of the object after it has been disposed unless otherwise explicitly noted.

    Returns void

  • Interrupt a kernel.

    Returns Promise<void>

    A promise that resolves when the kernel has interrupted.

    Uses the Jupyter Server API.

    The promise is fulfilled on a valid response and rejected otherwise.

    It is assumed that the API call does not mutate the kernel id or name.

    The promise will be rejected if the kernel status is 'dead' or if the request fails or the response is invalid.

  • Reconnect to a disconnected kernel.

    Returns Promise<void>

    A promise that resolves when the kernel has reconnected.

    This just refreshes the connection to an existing kernel, and does not perform an HTTP request to the server or restart the kernel.

  • Register a comm target handler.

    Parameters

    • targetName: string

      The name of the comm target.

    • callback: (comm: IComm, msg: ICommOpenMsg<"iopub" | "shell">) => void | PromiseLike<void>

      The callback invoked for a comm open message.

      Only one comm target can be registered to a target name at a time, an existing callback for the same target name will be overridden. A registered comm target handler will take precedence over a comm which specifies a target_module.

      If the callback returns a promise, kernel message processing will pause until the returned promise is fulfilled.

    Returns void

  • Register an IOPub message hook.

    Parameters

    • msgId: string
    • hook: (msg: IIOPubMessage<IOPubMessageType>) => boolean | PromiseLike<boolean>

      The callback invoked for the message.

      The IOPub hook system allows you to preempt the handlers for IOPub messages with a given parent_header message id. The most recently registered hook is run first. If a hook return value resolves to false, any later hooks and the future's onIOPub handler will not run. If a hook throws an error, the error is logged to the console and the next hook is run. If a hook is registered during the hook processing, it will not run until the next message. If a hook is disposed during the hook processing, it will be deactivated immediately.

      See also [[IFuture.registerMessageHook]].

    Returns void

  • Remove a comm target handler.

    Parameters

    • targetName: string

      The name of the comm target to remove.

    • callback: (comm: IComm, msg: ICommOpenMsg<"iopub" | "shell">) => void | PromiseLike<void>

      The callback to remove.

      The comm target is only removed if it matches the callback argument.

    Returns void

  • Send an execute_request message.

    Parameters

    • content: {
          allow_stdin?: boolean;
          code: string;
          silent?: boolean;
          stop_on_error?: boolean;
          store_history?: boolean;
          user_expressions?: JSONObject;
      }

      The content of the request.

      • Optionalallow_stdin?: boolean

        Whether to allow stdin requests. The default is true.

      • code: string

        The code to execute.

      • Optionalsilent?: boolean

        Whether to execute the code as quietly as possible. The default is false.

      • Optionalstop_on_error?: boolean

        Whether to the abort execution queue on an error. The default is false.

      • Optionalstore_history?: boolean

        Whether to store history of the execution. The default true if silent is False. It is forced to false if silent is true.

      • Optionaluser_expressions?: JSONObject

        A mapping of names to expressions to be evaluated in the kernel's interactive namespace.

    • OptionaldisposeOnDone: boolean

      Whether to dispose of the future when done.

    • Optionalmetadata: JSONObject

    Returns IShellFuture<IExecuteRequestMsg, IExecuteReplyMsg>

    A kernel future.

    See Messaging in Jupyter.

    This method returns a kernel future, rather than a promise, since execution may have many response messages (for example, many iopub display messages).

    Future onReply is called with the execute_reply content when the shell reply is received and validated.

    See also: [[IExecuteReply]]

  • Restart a kernel.

    Returns Promise<void>

    A promise that resolves when the kernel has restarted.

    Uses the Jupyter Server API and validates the response model.

    Any existing Future or Comm objects are cleared.

    It is assumed that the API call does not mutate the kernel id or name.

    The promise will be rejected if the kernel status is 'dead' or if the request fails or the response is invalid.

  • Send a shell message to the kernel.

    Type Parameters

    Parameters

    • msg: IShellMessage<T>

      The fully-formed shell message to send.

    • OptionalexpectReply: boolean

      Whether to expect a shell reply message.

    • OptionaldisposeOnDone: boolean

      Whether to dispose of the future when done.

      Send a message to the kernel's shell channel, yielding a future object for accepting replies.

      If expectReply is given and true, the future is done when both a shell reply and an idle status message are received with the appropriate parent header, in which case the .done promise resolves to the reply. If expectReply is not given or is false, the future is done when an idle status message with the appropriate parent header is received, in which case the .done promise resolves to undefined.

      If disposeOnDone is given and false, the future will not be disposed of when the future is done, instead relying on the caller to dispose of it. This allows for the handling of out-of-order output from ill-behaved kernels.

      All replies are validated as valid kernel messages.

      If the kernel status is 'dead', this will throw an error.

    Returns IShellFuture<IShellMessage<T>, IShellMessage<ShellMessageType>>

  • Shutdown a kernel.

    Returns Promise<void>

    A promise that resolves when the kernel has shut down.

    Uses the Jupyter Notebook API.

    On a valid response, closes the websocket, disposes of the kernel object, and fulfills the promise.

    The promise will be rejected if the kernel status is 'dead', the request fails, or the response is invalid.